小编ins*_*o10的帖子

如何让EasyMock模拟多次返回空列表

我希望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);
}
}
Run Code Online (Sandbox Code Playgroud)

java collections unit-testing easymock

4
推荐指数
1
解决办法
7546
查看次数

标签 统计

collections ×1

easymock ×1

java ×1

unit-testing ×1