【问题标题】:Mockito throwing 'Wanted but not invoked'Mockito 投掷“通缉但未调用”
【发布时间】:2017-04-12 13:04:49
【问题描述】:

我为我的应用编写了以下单元测试。我刚刚开始学习 UnitTesting 和 Mockito,所以异常/错误有点令人困惑。以下测试抛出了一个奇怪的异常。

Mockito 错误:

Wanted but not invoked:
mComicListFragmentPresenter.createComicListFromServerResponse(
    [com.myapp.comic.models.serverResponse.Result@387a8303, com.myapp.comic.models.serverResponse.Result@28cda624, com.myapp.comic.models.serverResponse.Result@1500b2f3]
);
-> at com.myapp.comic.ComicListFragmentPresenterUnitTest.testForCheckingSuccessBehaviorUponFetchingComicsFromServer(ComicListFragmentPresenterUnitTest.java:47)
Actually, there were zero interactions with this mock.

Wanted but not invoked:
mComicListFragmentPresenter.createComicListFromServerResponse(
    [com.myapp.comic.models.serverResponse.Result@387a8303, com.myapp.comic.models.serverResponse.Result@28cda624, com.myapp.comic.models.serverResponse.Result@1500b2f3]
);
-> at com.myapp.comic.ComicListFragmentPresenterUnitTest.testForCheckingSuccessBehaviorUponFetchingComicsFromServer(ComicListFragmentPresenterUnitTest.java:47)
Actually, there were zero interactions with this mock.

    at com.myapp.comic.ComicListFragmentPresenterUnitTest.testForCheckingSuccessBehaviorUponFetchingComicsFromServer(ComicListFragmentPresenterUnitTest.java:47)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

单元测试代码:

@RunWith(MockitoJUnitRunner.class)
public class MyUnitTest {

    @Mock
    ComicListFragment mComicListFragment;

    @Mock
    ComicListFragmentPresenter mComicListFragmentPresenter;

    List<Result> mResultList = Arrays.asList(new Result(), new Result(), new Result());
    @Test
    public void testForCheckingSuccessBehaviorUponFetchingComicsFromServer() {
       doNothing().when(mComicListFragment).onComicsFetchedSuccessfully(mResultList);
        Mockito.verify(mComicListFragmentPresenter, times(1)).createComicListFromServerResponse(mResultList);
        Mockito.verify(mComicListFragment, times(1)).onComicListCreationComplete();
    }
}

【问题讨论】:

  • 该错误表明您的测试未通过,因为未调用 Mockito.verify 中的方法。如果您在ComicListFragmentComicListFragmentPresenter 中发布代码,我们可以尽力帮助您
  • 那么您希望给createComicListFromServerResponse 打什么电话?您真正尝试测试的代码在哪里? (目前,您的测试方法看起来像是在模拟所有内容......)
  • 把演示者的代码放在这里

标签: java android mockito junit4


【解决方案1】:

当然!

你刺伤了一些调用 - 描述了它在某些情况下应该如何表现。并立即验证是否调用了某些东西。但是您没有在测试中运行任何方法。这就是为什么与您的模拟的交互为零的原因。

您的测试中也没有实例化任何真正的类。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-30
    • 2020-02-19
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    相关资源
    最近更新 更多