如何在父类中模拟@injected对象

时间:2016-11-09 07:15:22

标签: java spring unit-testing mocking mockito

我有一个@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和@Injected mock但它没有工作获得NPE。我试图注入Base类和父类,但没有运气。

1 个答案:

答案 0 :(得分:-1)

以下为我的作品:

@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。实际上没关系。

相关问题