我正在使用pythons mock.patch,并希望更改每个调用的返回值.以下是警告:正在修补的函数没有输入,因此我无法根据输入更改返回值.
这是我的代码供参考.
def get_boolean_response():
response = io.prompt('y/n').lower()
while response not in ('y', 'n', 'yes', 'no'):
io.echo('Not a valid input. Try again'])
response = io.prompt('y/n').lower()
return response in ('y', 'yes')
Run Code Online (Sandbox Code Playgroud)
我的测试代码:
@mock.patch('io')
def test_get_boolean_response(self, mock_io):
#setup
mock_io.prompt.return_value = ['x','y']
result = operations.get_boolean_response()
#test
self.assertTrue(result)
self.assertEqual(mock_io.prompt.call_count, 2)
Run Code Online (Sandbox Code Playgroud)
io.prompt只是一个独立于平台(python 2和3)版本的"输入".所以最终我试图模拟用户输入.我已经尝试使用列表作为返回值,但这并不能解决问题.
你可以看到,如果返回值是无效的,我将在这里得到一个无限循环.所以我需要一种方法来最终改变返回值,以便我的测试实际完成.
(回答这个问题的另一种可能的方法是解释我如何在单元测试中模仿用户输入)
不是这个问题的重复,主要是因为我没有能力改变输入.
答案中关于这个问题的评论之一是相同的,但没有提供答案/评论.
我有一个我正在测试的类,它具有另一个类的依赖(其实例被传递给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)
Run Code Online (Sandbox Code Playgroud)
这很好,但是"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 …Run Code Online (Sandbox Code Playgroud)