【问题标题】:How to get an EasyMock mock to return an empty list multiple times如何让 EasyMock 模拟多次返回空列表
【发布时间】:2011-02-04 17:44:55
【问题描述】:

我希望 EasyMock 模拟能够多次期待一个空列表,即使第一次返回的列表中添加了元素。

这可能吗?由于在期望中创建的空列表在整个重播中持续存在,因此保留了在两次调用之间添加到其中的任何元素。

这是一个代码示例,显示了我要避免的情况:

public class FakeTest {

private interface Blah {

    public List<String> getStuff();
};

@Test
public void theTest(){

    Blah blah = EasyMock.createMock(Blah.class);

    //Whenever you call getStuff() an empty list should be returned
    EasyMock.expect(blah.getStuff()).andReturn(new ArrayList<String>()).anyTimes();

    EasyMock.replay(blah);

    //should be an empty list
    List<String> returnedList = blah.getStuff();
    System.out.println(returnedList);

    //add something to the list
    returnedList.add("SomeString");
    System.out.println(returnedList);

    //reinitialise the list with what we hope is an empty list
    returnedList = blah.getStuff();

    //it still contains the added element
    System.out.println(returnedList);

    EasyMock.verify(blah);
}
}

【问题讨论】:

    标签: java unit-testing collections easymock


    【解决方案1】:

    您可以使用 andStubReturn 每次生成一个新列表。

    //Whenever you call getStuff() an empty list should be returned
    EasyMock.expect(blah.getStuff()).andStubAnswer(new IAnswer<List<String>>() {
            @Override
            public List<Object> answer() throws Throwable {
                return new ArrayList<String>();
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-23
      • 1970-01-01
      • 2011-02-10
      • 1970-01-01
      • 1970-01-01
      • 2011-06-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多