如何模拟被调用两次的方法,并使其返回不同的值。要想像一下,这里是代码:
def method(self, param):
# here I have the logic if param is equal to 1 -> return [1,2,3], if param is equal to 2 -> return [a,s,d]
def method_x(self, param_x):
# here uses method returned values with 1 or 2
def main():
one = self.method(1)
two = self.method(2)
three = self.method_x(one)
four = self.method_x(two)
测试:
def setUp(self):
self.c = py_file.Class()
def test_main(self):
self.c.method = MagicMock()
self.c.main()
self.c.method.assert_any_call(1)
self.c.method.assert_any_call(2)
self.assertEqual(2, self.c.method.call_count)
# but the problem comes when I need to use for other methods method(1) in three and method(2) in four
...
我试图这样使用side_effect
:
self.c.method = MagicMock(side_effect=[[1,2,3],[a,s,d]])
# this way running test one has 1,2,3 values and two has a,s,d
但是随后涉及到four
和five
的值时,我得到了(像c.method.side_effects= [[1,2,3],[a,s,d]] and then for four use c.method.side_effects[0] and for five with [1]
:
TypeError: 'listiterator' object is unsubscriptable
如何通过正确的值来更正测试中的变量-如何正确模拟和设置返回值?
使用Python2.6.6,模拟1.0.0