我有一个正在测试的类,它具有另一个类的依赖项(其实例被传递给 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 的多个实例(其值由从 mockobj 返回的内容产生)。
有点像我在想的(这当然行不通):
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
我如何实现这种“ifcallwith”的语义?