我目前正在测试我的python代码,并对raw_input有疑问.这是我的功能:
def answer():
ans = raw_input('enter yes or no')
if ans == 'yes':
print 'you entered yes'
return 'yes'
if ans == 'no':
some_value = raw_input('enter some value: ')
print 'you entered no'
return some_value
我正在用这种方式测试第一个if语句:
with mock.patch('__builtin__.raw_input', return_value= 'yes'):
assert answer() == 'yes'
但是我如何检查无声明?如何在模拟中进行模拟?
解决方法:
with mock.patch('__builtin__.raw_input', side_effect=['yes']):
assert answer() == 'yes'
with mock.patch('__builtin__.raw_input', side_effect=['no', 'maybe']):
assert answer() == 'maybe'
If side_effect is an iterable then each call to the mock will return the next value from the iterable.
The side_effect can also be any iterable object. Repeated calls to the mock will return values from the iterable (until the iterable is exhausted and a StopIteration is raised):
06001
标签:python,unit-testing,mocking