java - 如何让 EasyMock 模拟多次返回一个空列表

标签 java unit-testing collections 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);
}
}

最佳答案

您可以使用 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>();
        }
    }

关于java - 如何让 EasyMock 模拟多次返回一个空列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4901181/

相关文章:

java - 计算山谷

java - 不使用原始类型无法获得泛型的类对象

java - 如何迭代两个多重映射并打印文件中的差异?

java - 线程作为 Java 对象

java - Apache POI OPCPackage 无法保存 Jasper 报告生成的 XLSX

java - 从复杂的 Json 字符串中获取值

php - 是否有基于 PHP 的 Python Nose 实现?

c++ - 对 COM 端口抽象库进行单元测试的最佳方法是什么?

ios - 回调方法 ios 的单元测试用例

java - 如何在 JAVA 中进行 REST Web 服务调用?