在我的javaee项目中有一个接口:
public interface SomeInterface{...}
和多个实现:
@Stateless(name = "ImplementationA")
public class ImplementationA implements SomeInterface{...}
@Stateless(name = "ImplementationB")
public class ImplementationB implements SomeInterface{...}
为了访问所有实现,我在另一个类中有以下内容:
@Singelton
public class AnotherClass{
@Inject
@Any
private Instance<SomeInterface> impls;
public SomeInterface someMethod(){
for(SomeInterface imp : impls){
if(imp.oneMethod()){
return imp;
}
}
return null;
}
}
如果我想对这个“AnotherClass”进行单元测试,我该如何模拟
Instance<SomeInterface> impls
场?
尝试@Mock,@ Spy,无法从Mockito内部得到适当的嘲弄,当测试运行时,“impls”始终为null。
单元测试本身如下所示:
@RunWith(MockitoJUnitRunner.class)
public class SomeTestClass {
@InjectMocks
AnotherClass anotherClass;
@Spy // Here I tried @Mock as well
private Instance<SomeInterface> impls;
@Test
public void TestSomeMethod(){
Assert.assertTrue( anotherClass.someMethod() == null ); // <- NullPointerException here, which indicates the impls is null instead of anotherClass.
}
}
必须在“AnotherClass”中添加另一个方法来接受Instance impls的实例,该实例是在单元测试中创建的,但是很难实现另一个不相关的方法只是为了单元测试而添加。 / p>
知道单元测试的正确方法是什么样的?
Mockito和Junit版本:
group: 'junit', name: 'junit', version: '4.12'
group: 'org.mockito', name: 'mockito-core', version:'2.12.0'
提前致谢。
答案 0 :(得分:1)
你可以尝试做什么:
impls.xxxx()
来调用一个真正的方法(猜测这是默认行为)。也许首先尝试初始化:
@RunWith(MockitoJUnitRunner.class)
public class SomeTestClass {
@InjectMocks
AnotherClass anotherClass;
@Spy
private Instance<SomeInterface> impls;
// init here
@Before
public void initMocks() {
MockitoAnnotations.initMocks(this);
}
@Test
public void TestSomeMethod(){
anotherClass.someMethod(); // <- NullPointerException here, which indicates the impls is null instead of anotherClass.
}
}
此init调用需要位于基类或测试运行器中。
奇怪的是,如果没有它就行不通,我想如果你使用MockitoJUnitRunner它应该可以工作。