Mockito Expects()函数不会引发异常
我正在使用Mockito来测试KafkaProducer通过此行发送一次: 期望(KafkaProducer,times = 0)。发送(...) 当times = 2时,在控制台中抛出VerificationError,并且测试失败,但是,当times = 0且抛出InvocationError时(通过pdb而非控制台看到),但是程序正常通过测试通过。
expect(KafkaProducer, times=2).send(...)
# Instantiates a KafkaProducer and calls .send()
send_to_kafka()
# Verify that send was called twice
verifyNoUnwantedInteractions()
预期为0,它将通过pytest,但在我遍历pdb时会引发错误。
ERROR:
Wanted times: 0, actual times: 1
Traceback (most recent call last):
File "/Users/juswei/cosmosx/collectors/breeze/src/kafka_interface.py", line 46, in push_breeze_runs
'BREEZE-COLLECTOR-TOPIC', data.encode(), timestamp_ms=timestamp)
File "/usr/lib/python3.6/site-packages/mockito/mocking.py", line 88, in new_mocked_method
self, method_name, *args, **kwargs)
File "/usr/lib/python3.6/site-packages/mockito/mocking.py", line 44, in remembered_invocation_builder
return invoc(*args, **kwargs)
File "/usr/lib/python3.6/site-packages/mockito/invocation.py", line 162, in __call__
matching_invocation.should_answer(self)
File "/usr/lib/python3.6/site-packages/mockito/invocation.py", line 309, in should_answer
% (verification.wanted_count, actual_count))
mockito.invocation.InvocationError:
Wanted times: 0, actual times: 1
答案 0 :(得分:0)
这个问题有点令人困惑,因为您说您希望生产者调用send
一次,但是使用times=0
则意味着永远不会。
通常:
In [35]: m = mock()
In [36]: expect(m, times=0).foo()
Out[36]: <mockito.invocation.AnswerSelector at 0x13b36b8>
In [37]: verifyNoUnwantedInteractions(m)
In [38]: m.foo()
<snip>
InvocationError:
Wanted times: 0, actual times: 1
t.i。如果您不想永远,则foo()
引发InvocationError
。
当您想要 一次时,您可能会得到
In [39]: m = mock()
In [40]: expect(m, times=1).foo()
Out[40]: <mockito.invocation.AnswerSelector at 0x5017130>
In [41]: verifyNoUnwantedInteractions(m)
<...>
VerificationError:
Wanted but not invoked:
foo()
Instead got:
Nothing
t.i。 VerificationError
。 (如果您两次调用过foo
,您将再次收到InvocationError
。)您得到的错误很简单:它是使用verify*
函数抛出的,还是它抛出了下面的代码?在调用嘲笑函数时进行测试?
如果被测系统实际上在单独的线程中,或者通常在吞噬所有错误,这可能会很棘手。因为这样就可以为您处理在该系统中引发的任何异常,最终它可能只会被记录下来并且测试可以神奇地通过。但这取决于您的测试系统。
但是,如果这样,最好事先放宽/没有期望,然后仅在测试代码中进行验证。
when(Producer).send(...) # <-- ... = anything is okay
testtest()
verify(Producer).send('foo', 'bar') # <-- as specific as needed