通过嘲笑创建模拟列表 [英] Create a mocked list by mockito

查看:70
本文介绍了通过嘲笑创建模拟列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to create a mocked list to test below code:

 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;
}

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

But when the test run it throw exception at line:

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:模拟将在for循环中进行循环操作.

OK, this is a bad thing to be doing. Don't mock a list; instead, mock the individual objects inside the list. See Mockito: mocking an arraylist that will be looped in a for loop for how to do this.

此外,为什么还要使用PowerMock?您似乎不需要执行任何需要PowerMock的操作.

Also, why are you using PowerMock? You don't seem to be doing anything that requires PowerMock.

但是造成问题的真正原因是,在完成存根之前,您在两个不同的对象上使用了when.当您调用when并提供要尝试存根的方法调用时,那么在Mockito或PowerMock中要做的下一步就是指定调用该方法时发生的事情-即执行部分.在您再次调用when之前,每次调用when都必须跟随一个并且只有一个调用thenReturn.您打了两次电话给when而没有呼叫thenReturn-这是您的错误.

But the real cause of your problem is that you are using when on two different objects, before you complete the stubbing. When you call when, and provide the method call that you are trying to stub, then the very next thing you do in either Mockito OR PowerMock is to specify what happens when that method is called - that is, to do the thenReturn part. Each call to when must be followed by one and only one call to thenReturn, before you do any more calls to when. You made two calls to when without calling thenReturn - that's your error.

这篇关于通过嘲笑创建模拟列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆