也许这是一个新手问题,但找不到答案。
我需要在Mockito中添加方法。如果该方法具有“简单”参数,那么我可以做到。例如,具有两个参数的查找方法,汽车颜色和门数:
when(carFinderMock.find(eq(Color.RED),anyInt())).thenReturn(Car1);
when(carFinderMock.find(eq(Color.BLUE),anyInt())).thenReturn(Car2);
when(carFinderMock.find(eq(Color.GREEN), eq(5))).thenReturn(Car3);
问题在于,find参数是一个复杂的对象。
mappingFilter = new MappingFilter();
mappingFilter.setColor(eq(Color.RED));
mappingFilter.setDoorNumber(anyInt());
when(carFinderMock.find(mappingFilter)).thenReturn(Car1);
此代码无效。错误是“无效使用参数匹配器!期望有1个匹配器,已记录2个”。
无法修改“查找”方法,它必须是MappingFilter参数。
我想我必须做一些事情来指示Mockito,当mappingFilter.getColor为RED,而mappingFilter.getDoorNumber为任意值时,它必须返回Car1(其他两个句子也是如此)。但是如何?
使用Hamcrest匹配器,如the documentation中所示:
when(carFinderMock.find(argThat(isRed()))).thenReturn(car1);
其中isRed()
定义为
private Matcher<MappingFilter> isRed() {
return new BaseMatcher<MappingFilter>() {
// TODO implement abstract methods. matches() should check that the filter is RED.
}
}
您需要正确实现MappingFilter的equals()
方法。在equals()中,您应该只比较颜色,而不是doorNumber。
最简单的形式,应该看起来像这样-
@Override
public boolean equals(Object obj) {
MappingFilter other = (MappingFilter) obj;
return other.getColor() == this.getColor();
}
此外,您应该按照以下方式简单地构成MappingFilter,而不要使用诸如eq之类的任何匹配器>
mappingFilter = new MappingFilter();
mappingFilter.setColor(Color.RED);
mappingFilter.setDoorNumber(10); //Any integer
因为2.1.0