我有两个几乎相同的外观类:
class Foo1 {
private Bar bar1;
private Bar bar2;
public void setBar1(Bar bar1) {
this.bar1 = bar1;
}
public void setBar2(Bar bar2) {
this.bar2 = bar2;
}
}
class Foo2 {
private Bar bar1;
private Bar bar2;
public Foo2(Bar bar1, Bar bar2) {
this.bar1 = bar1;
this.bar2 = bar2;
}
}
所以这是setters vs constructor。问题是@InjectMocks仅适用于下面测试中的第一个类:
@RunWith(MockitoJUnitRunner.class)
public class Test {
@Mock
private Bar bar1;
@Mock
private Bar bar2;
@InjectMocks
private Foo1 sut;
}
要测试第二课我必须手动完成,因为对于两个Bar参数,同样的模拟由@InjectMocks选择(它是随机选择)
@RunWith(MockitoJUnitRunner.class)
public class Test {
@Mock
private Bar bar1;
@Mock
private Bar bar2;
private Foo2 sut;
@Before
public void setUp() {
sut = new Foo2(bar1, bar2);
}
}
也许我误解了一些事情但是如何用@InjectMocks正确地测试二等?也许这是Mockito的错误或特征?
经过测试:
更新:命名模拟@Mock(名称="模拟")在这种情况下不起作用