I have a class that I'm testing that has a dependency on another class (an instance of which is passed to the CUT init method). I want to mock this class using the Python Mock library.
I have something like:
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)
This is good, but the methodfromdepclass method is a parameterized method, and as such I want to create one mock object, in which, depending on what arguments are passed to the method fromdempclass, it returns different values.
I want this parameterized behavior to be that I want to create several instances of ClassUnderTest that contain different values ββ(whose values ββare created using what is returned from mockobj).
What I think (this of course does not work):
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
How to achieve this "semantics" using "tailored"?
python unit-testing mocking python-mock
Adam Parkin Oct 05 '11 at 18:09 2011-10-05 18:09
source share