我有一个@Inject对象,我需要在我的测试类使用@InjectMocks时模拟其抛出NPE
下面是我的类 的结构Class ChildClass extends ParentClass
{
public myMethod(){
String myval=callParentClassMethod();
}
Class ParentClass{
@Inject
private MyService myservice;
//there is no constructor or setter method for this injected object
protected String callParentClassMethod(){
retrun myservice.getStringval();
}
}
你能建议一下如何模拟这个MyService对象吗?我已经使用了@Mock和@ inject mock,但它没有工作得到NPE。我试着同时注入基类和父类,但没有运气
我的作品:
@RunWith(MockitoJUnitRunner.class)
public class MyTest {
@InjectMocks
private ChildClass childClass = new ChildClass();
@Mock
private MyService service;
@Test
public void test1() {
childClass.myMethod();
}
}
我已经上传了带有测试的示例项目到https://github.com/shurick-k/mock-test
您没有指定使用什么类型的@Inject注释,所以我假设它来自javaee-api。其实没关系。