也许这是一个新手问题,但找不到答案。
我需要用 Mockito stub 一个方法。如果该方法具有“简单”参数,那么我可以做到。例如,带有两个参数的 find 方法,汽车颜色和门数:
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 个”。
不能修改“find”方法,需要是MappingFilter参数。
我想我必须做“某事”来指示 Mockito,当 mappingFilter.getColor 为红色且 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.
}
}
关于java - Mockito:以复杂对象作为参数的 stub 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15140467/