Mockito期望()不引发例外



mockito Expect((函数不投掷异常

我正在使用Mockito测试Kafkaproducer与此行发送一次:期待(kafkaproducer,times = 0(。当Times = 2时,将验证器放在控制台中,并且测试失败,但是当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

这个问题有点令人困惑,因为您说您期望生产者调用 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

,当您 WANT 一旦您可以得到

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*函数投掷的,还是在调用模拟函数时会准确地抛出测试的代码?

如果正在测试的系统实际上在单独的线程中,或者通常正在吃所有错误,则可能会变得棘手。因为那时可以为您处理任何例外,最终可能会记录下来,并且测试神奇地通过。但这取决于您的测试系统。

但是,如果是这样,最好先有LAX/NONE期望,然后仅在测试代码中进行验证。

when(Producer).send(...)  # <-- ... = anything is okay
testtest()
verify(Producer).send('foo', 'bar')  # <-- as specific as needed

相关内容

  • 没有找到相关文章

最新更新