2016-11-09 132 views
0

我有一个@Inject对象,我需要讥笑它投掷NPE同时使用@InjectMocks在我的测试类如何嘲笑在父类@injected对象

下面是我的类的结构

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和@Injected模拟,但它无法获得NPE。我试图注入基类和父类,但没有运气。我

回答

0

以下工作:

@RunWith(MockitoJUnitRunner.class) 
public class MyTest { 
    @InjectMocks 
    private ChildClass childClass = new ChildClass(); 

    @Mock 
    private MyService service; 

    @Test 
    public void test1() { 
     childClass.myMethod(); 
    } 
} 

UPDATE 我上传示例项目与测试https://github.com/shurick-k/mock-test

你没有指定所到底是什么类型的@Inject注解使用,所以我认为它来自javaee-api。其实没关系。

+0

谢谢Shurick回复。我在调用注入服务时仍然获得NPE。是否有其他方式 –