2013-02-28 160 views
9

也许这是一个新手问题,但找不到答案。Mockito:以复杂对象作为参数的存根方法

我需要用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(并且对于另外两个句子也是一样的)。 但是如何?

回答

10

使用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. 
    } 
} 
+0

非常好,完美的作品:D – 2013-02-28 16:54:20

1

您需要正确执行equals()方法MappingFilter。在等于()你应该只比较颜色而不是门号

在最简单的形式,它应该是这样的 -

@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 
+0

感谢您的回答! 是否可以在不执行equals方法的情况下执行?例如,过滤器有20个字段,我只想测试何时颜色和门号码具有指定的值,并且在另一段代码中,当颜色和汽车类型具有指定的值(没有比较门号)时,等等 – 2013-02-28 16:30:57

+0

好吧,或者,正如@JB Nizet指出的那样,似乎是这样做的方式。 – Gopi 2013-02-28 16:35:54

相关问题