如何模拟具有特定值的列表

时间:2011-03-28 12:15:27

标签: java easymock

我有一个方法:

expect(processor.process(arg1, list));
expectLastCall().anyTImes();

现在,我需要列表包含某些值。问题是必须以正确的顺序将值添加到列表中,否则列表将不等于真实列表。所以我不能只创建一个新列表并在其中添加值,因为如果方法process改变了将值添加到列表中的顺序,则测试将失败。 我试过这个

List list=createMock(List.class);
expect(list.add(value1)).andReturn(true);
expect(lst.add(value2)).andReturn(true);

但他给出了这个例外:

java.lang.AssertionError: 
  Unexpected method call process(arg, [Listvalue1,Listvalue2]):
    process(arg, EasyMock for interface java.util.List): expected: 1, actual: 0

非常感谢。

1 个答案:

答案 0 :(得分:2)

您可以使用IAnswerEasyMock.getCurrentArguments(),然后手动断言列表的内容

expect(processor.process(arg1, list));
expectLastCall().anyTimes().andAnswer(new IAnswer<Object>() {
    public Object answer() throws Throwable {
        List myList = (List) EasyMock.getCurrentArguments()[1];
        // do your assertions on the list here (or change the order as required)
    }    
});

使用EasyMock.getCurrentArguments()的一个重大缺点是它不是“重构安全”(如果你更改参数的顺序,它将破坏测试)。

希望它有所帮助。

相关问题