有效构造:
@InjectMocks
SomeClass sc = mock(SomeClass.class);
无效的构造:
@InjectMocks
@Mock
SomeClass sc;
我想将模拟注入(inject)另一个模拟。我只想使用注释样式。
为什么在 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());
}
}
最佳答案
听起来您正在尝试做一些没有实际意义的事情。你不应该 需要 将任何依赖项注入(inject)你的模拟,因为根据定义模拟没有任何行为,直到你用 when(mock.someMethod()).thenAnswer()< 定义它
或一些变体。
(除非您正在使用 spy()
,但您明确表示您正在使用 @Mock
)。
也许您可以解释您的用例以及为什么要尝试将依赖项注入(inject)模拟?
关于java - 为什么不能同时使用 Mock 和 InjectMocks?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23632330/