java - 通过 mockito 创建一个模拟列表

标签 java unit-testing junit mocking mockito

我想创建一个模拟列表来测试以下代码:

 for (String history : list) {
        //code here
    }

这是我的实现:

public static List<String> createList(List<String> mockedList) {

    List<String> list = mock(List.class);
    Iterator<String> iterHistory = mock(Iterator.class);

    OngoingStubbing<Boolean> osBoolean = when(iterHistory.hasNext());
    OngoingStubbing<String> osHistory = when(iterHistory.next());

    for (String history : mockedList) {

        osBoolean = osBoolean.thenReturn(true);
        osHistory = osHistory.thenReturn(history);
    }
    osBoolean = osBoolean.thenReturn(false);

    when(list.iterator()).thenReturn(iterHistory);

    return list;
}

但是当测试运行时,它会在以下行抛出异常:

OngoingStubbing<DyActionHistory> osHistory = when(iterHistory.next());

详情:

org.mockito.exceptions.misusing.UnfinishedStubbingException: 
Unfinished stubbing detected here:
-> at org.powermock.api.mockito.PowerMockito.when(PowerMockito.java:495)

E.g. thenReturn() may be missing.
Examples of correct stubbing:
    when(mock.isOk()).thenReturn(true);
    when(mock.isOk()).thenThrow(exception);
    doThrow(exception).when(mock).someVoidMethod();
Hints:
 1. missing thenReturn()
 2. you are trying to stub a final method, you naughty developer!

我该如何解决?谢谢

最佳答案

好吧,这是一件坏事。不要模拟列表;相反,模拟列表中的各个对象。见 Mockito: mocking an arraylist that will be looped in a for loop如何做到这一点。

另外,您为什么要使用 PowerMock?你似乎没有做任何需要 PowerMock 的事情。

但问题的真正原因是您在完成 stub 之前在两个不同的对象上使用了 when。当您调用 when 并提供您尝试 stub 的方法调用时,您在 Mockito 或 PowerMock 中所做的下一件事就是指定调用该方法时会发生什么 - 也就是说,执行 thenReturn 部分。每次对 when 的调用必须跟一个且只有一个对 thenReturn 的调用,然后再对 when 进行任何调用。您对 when 进行了两次调用而没有调用 thenReturn - 这是您的错误。

关于java - 通过 mockito 创建一个模拟列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18514033/

相关文章:

java - 如何使用简单日期格式格式化没有年份的日期?

java - 什么是普通 JavaBeans 和普通 Java 类?

javascript - 如何用 sinon 模拟 hapi.js 回复以进行单元测试

java - 警告: Autowired annotation is not supported on static fields的原因是什么

java - 打包非模块化JavaFX应用程序

c# - 自动测试属性 getter/setter

javascript - Chai .js : How to correctly use the `and` getter in a language chain

java - 在 Junit 中扩展 ParentRunner

java - 使用 Jenkins 进行自动化 Weblogic 服务测试

java - 什么导致junit警告org.junit.platform.launcher.core.EngineDiscoveryOrchestrator lambda$logTestDescriptorExclusionReasons$7