gpt4 book ai didi

java - 如何验证 Mockito 中的所有方法调用?

转载 作者:搜寻专家 更新时间:2023-11-01 03:51:50 25 4
gpt4 key购买 nike

我有一个 JUnit 测试,其中包含一些使用 Mockito 测试的方法。我对 EasyMock 有相当丰富的经验(虽然不是最近的)所以我是这样组织的:

@Before
public void before() {
myAPI = mock(MyAPI.class);
}

@After
public void after() {
verify(myAPI);
reset(myAPI);
}

如果需要,这些方法会在 mock 上注册一些调用。

但我有一个异常(exception):

org.mockito.exceptions.misusing.UnfinishedVerificationException: Missing method call for verify(mock) here: -> at de.datev.shared.spdvz.util.UserInfoUtilTest.after(UserInfoUtilTest.java:45)

Example of correct verification: verify(mock).doSomething()

我知道我可以做 verify(myAPI).doSomething(someArgs) 但是:

  1. 我必须在每种方法中都这样做
  2. 我必须重复与 when
  3. 中使用的参数相同的参数

是否有任何方法可以简单地验证是否实际调用了在 when 上注册的所有方法? EasyMock 就是这样工作的,而且非常方便......

最佳答案

我认为这是不可能的。 Here是一个古老的讨论,其中两个维护者正在陈述他们对此类功能的看法。讨论已经很老了,但据我所知,当前的 Mockito 版本仍然不支持它。

In Mockito verification is explicit. So you basically verify(assert) if a particular invocations has already taken place or not and it's up to you to choose what's important to be examined. Mockito has also much stronger separation between stubbing and mocking functionality. Thus, it let you stub some calls to make the code pass the path you intended without verifying the calls have happened. Moreover, you are not obligated to sub invocations unless you are happy with default values Mockito provides you.

Such an approach separates test setup logic from test verification one much better increasing readability.

Few words about why mockito doesn't promote verifying stubbed methods.

  1. Simplification. Back in the old days, when mock frameworks were widely unknown we've been hand-writing our stubs. But I don't remember a single case where we wanted to verify that the stub was actually called. The reason was simple: stubbed methods are implicitly verified: by the fact that stubbed value is essential in processing.

  2. I saw tests where not having separation of stubbing and 'expecting' was actually harmful. The developer added return-value expectation because mock screamed with UnexpectedOperation. But he did not check if the value returned by mock was actually used... Simplifying stubbing puts accent on something more interesting: if stubbed value is used correctly.

关于java - 如何验证 Mockito 中的所有方法调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24527391/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com