最简单的方法是使用2个测试类而不是1个测试类,因为它在执行测试方法时已经太迟了,因为模拟已经被注入(除非使用应该避免的反射)。
第一个测试
@RunWith(MockitoJUnitRunner.class)
public class Test1 {
@Mock
private SomeDependency<T> obj;
@InjectMocks
private SomeClass mainObj;
@Test
public void dependencyShouldBeNotNull() {
//here I need one value of SomeDependency obj
assertEquals(2, mainObj.method());
}
}
第二个测试
@RunWith(MockitoJUnitRunner.class)
public class Test2 {
@InjectMocks
private SomeClass mainObj;
@Test
public void dependencyShouldBeNull() {
//here I need SomeDependency obj to be null
assertEquals(1, mainObj.method());
}
}
如果你想只有一个测试类做到这一点,它仍然是可能的,但它更像是一个黑客因为你需要一个不是传统方法的条件注入,所以你需要用MockitoAnnotations.initMocks(obj)
以编程方式注入模拟。
而不是直接注入嘲笑成测试类的,我们需要依靠将包含或不现场obj
,如果不存在任何将被注入所以这将是null
否则你将有一个模拟注入的包装类。
public class TestInjectMocks {
/**
* Small interface that will be implemented by the wrapper classes
* only used to get the main class
*/
public interface TestConfig {
SomeClass getSomeClass();
}
@Test
public void dependencyShouldBeNotNull() {
// This class will allow to get an instance of SomeClass
// with the field injected
TestConfig obj = new TestConfig() {
@Mock
private SomeDependency<T> obj;
@InjectMocks
private SomeClass mainObj;
@Override
public SomeClass getSomeClass() {
return mainObj;
}
};
MockitoAnnotations.initMocks(obj);
SomeClass mainObj = obj.getSomeClass();
//here I need one value of SomeDependency obj
assertEquals(2, mainObj.method());
}
@Test
public void dependencyShouldBeNull() {
// This class will allow to get an instance of SomeClass
// without the field injected
TestConfig obj = new TestConfig(){
@InjectMocks
private SomeClass mainObj;
@Override
public SomeClass getSomeClass() {
return mainObj;
}
};
MockitoAnnotations.initMocks(obj);
SomeClass mainObj = obj.getSomeClass();
//here I need SomeDependency obj to be null
assertEquals(1, mainObj.method());
}
}
注:我们称之为MockitoAnnotations.initMocks(obj)
明确不需要注释@RunWith(MockitoJUnitRunner.class)
了。
'obj = null;'? – Seelenvirtuose
@Seelenvirtuose我试过了,它不起作用 –
设置'obj = null'不起作用,如果你想要'obj == null' ???你应该解释更多你想要的东西。事实上,这个问题很不明确。 – Seelenvirtuose