python单元测试mock_单元测试-具有多次调用方法的Python Mock对象

我有一个正在测试的类,该类具有依赖关系的另一个类(该类的实例被传递给CUT的init方法)。 我想使用Python Mock库来模拟此类。

我所拥有的是这样的:

mockobj = Mock(spec=MyDependencyClass)

mockobj.methodfromdepclass.return_value = "the value I want the mock to return"

assertTrue(mockobj.methodfromdepclass(42), "the value I want the mock to return")

cutobj = ClassUnderTest(mockobj)

没关系,但是“ methodfromdepclass”是参数化的方法,因此我想创建一个单独的模拟对象,其中根据将哪些参数传递给methodfromdepclass来返回不同的值。

我想要此参数化行为的原因是我想创建ClassUnderTest的多个实例,这些实例包含不同的值(其值由从嘲笑对象返回的值产生)。

Kinda我在想什么(这当然行不通):

mockobj = Mock(spec=MyDependencyClass)

mockobj.methodfromdepclass.ifcalledwith(42).return_value = "you called me with arg 42"

mockobj.methodfromdepclass.ifcalledwith(99).return_value = "you called me with arg 99"

assertTrue(mockobj.methodfromdepclass(42), "you called me with arg 42")

assertTrue(mockobj.methodfromdepclass(99), "you called me with arg 99")

cutinst1 = ClassUnderTest(mockobj, 42)

cutinst2 = ClassUnderTest(mockobj, 99)

# now cutinst1 & cutinst2 contain different values

如何实现这种“ ifwithwith”语义?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值