【问题标题】:How to mock @injected object at parent class如何在父类中模拟@injected 对象
【发布时间】:2016-11-09 07:15:22
【问题描述】:

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

【问题讨论】:

    标签: java spring unit-testing mocking mockito


    【解决方案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。其实没关系。

    【讨论】:

    • 感谢舒里克的回复。我在调用 Injected Service 时仍然收到 NPE。还有其他方法吗
    • @DhrumilShah 你有解决办法吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-07
    • 1970-01-01
    • 2018-11-15
    • 2021-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多