尝试测试一种采用对象列表并返回对象排序列表的方法。排序是基于将第一个元素放在具有空字符串值的列表上而进行的。测试失败,并出现以下错误:
java.lang.AssertionError:
Unexpected method call LoggerConfig.getName():
LoggerConfig.getName(): expected: 1, actual: 2
Run Code Online (Sandbox Code Playgroud)
这里的问题是希望有明确的通话次数。在这里,似乎该方法被调用太多,这引发了一个异常,即该方法已被调用过多次。在第一个方法调用超出限制(从EasyMock指南中获取)后,立即发生故障。问题是在这种情况下如何解决?我在哪里做错了?
EasyMock代码:
public class SorterTest {
private Sorter tested;
LoggerConfig item1;
LoggerConfig item2;
LoggerConfig item3;
List<LoggerConfig> sortedList;
@Before
public void setUp() {
tested = new Sorter();
}
private List<LoggerConfig> makeUnsortedList() {
item1 = EasyMock.mock(LoggerConfig.class);
item2 = EasyMock.mock(LoggerConfig.class);
item3 = EasyMock.mock(LoggerConfig.class);
EasyMock.expect(item1.getName()).andReturn("com.core");
EasyMock.expect(item2.getName()).andReturn("");
EasyMock.expect(item3.getName()).andReturn("com.core.FOO");
List<LoggerConfig> unsortedList = new ArrayList<>();
unsortedList.add(item1);
unsortedList.add(item2);
unsortedList.add(item3);
return unsortedList;
}
@Test
public void testSort() {
List<LoggerConfig> unsortedList = makeUnsortedList();
EasyMock.replay(item1,item2,item3);
List<LoggerConfig> sortedList = tested.sort(unsortedList);
assertTrue(sortedList.get(0).getName().isEmpty());
assertTrue(sortedList.get(1).equals("com.core") || sortedList.get(1).equals("com.fwk.core.EBCTestClass"));
assertTrue(sortedList.get(2).equals("com.core") || sortedList.get(2).equals("com.core.FOO"));
}
}
Run Code Online (Sandbox Code Playgroud)
测试以下方法:
class Sorter {
List<LoggerConfig> sort(List<LoggerConfig> unSortedList) {
List<LoggerConfig> sortedList = new ArrayList<>(unSortedList);
Collections.sort(sortedList, new Comparator<LoggerConfig>() {
@Override
public int compare(LoggerConfig o1, LoggerConfig o2) {
return (o1.getName().compareTo(o2.getName()));
}
});
return sortedList;
}
}
Run Code Online (Sandbox Code Playgroud)
它getName()作为排序的一部分进行调用(可能多次调用,具体取决于算法),然后在验证中再次调用。由于您实际上对它的调用次数并不感兴趣(因为它不属于已测试合同的一部分),因此请删除默认限制。为此,请替换andReturn为andStubReturn:
EasyMock.expect(item1.getName()).andStubReturn("com.core");
EasyMock.expect(item2.getName()).andStubReturn("");
EasyMock.expect(item3.getName()).andStubReturn("com.core.FOO");
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5533 次 |
| 最近记录: |