【发布时间】:2014-05-13 13:15:00
【问题描述】:
有效构造:
@InjectMocks
SomeClass sc = mock(SomeClass.class);
无效的构造:
@InjectMocks
@Mock
SomeClass sc;
我想将模拟注入另一个模拟。我只想使用注释样式。
为什么在 Mockito 中禁止二次构造?
更新
示例:
public class ArrTest {
private SomeClass someClass;
public List<String> foo(){
anotherMethod(); // I suppose that this method works. I want to test it separately.
//logic which I need to test
return someClass.doSmth();// I suppose that this method works. I want to test it separately.
}
public void anotherMethod(){
///...
}
}
public class SomeClass {
public List<String> doSmth(){
return null;
}
}
测试:
public class ArrTestTest {
@InjectMocks
ArrTest arrTest = Mockito.mock(ArrTest.class);
@Mock
SomeClass someClass;
@Test
public void fooTest(){
Mockito.when(someClass.doSmth()).thenReturn(new ArrayList<String>());
Mockito.doNothing().when(arrTest).anotherMethod();
System.out.println(arrTest.foo());
}
}
【问题讨论】:
-
通过模拟
arrTest,其所有方法和字段的实现变得无关紧要。Mockito.when().thenReturn()调用定义了“实现”(我松散地使用了这个术语)。 Mockito 无法将模拟注入arTest模拟,因为没有要注入的字段,请参阅下面 @jeff-bowman 的答案。看起来您正在尝试做的是部分模拟,在这种情况下,您需要创建一个@Spy和/或将行为定义为when(mock.someCall().thenCallRealMethod()。
标签: java unit-testing testing mockito