【问题标题】:How to get away with NPE for @Inject field while unit testing?单元测试时如何摆脱 @Inject 字段的 NPE?
【发布时间】:2017-04-19 19:42:04
【问题描述】:

我正在为以下代码编写单元测试,即使我在模拟这些字段,我也得到了 NPE,我该如何解决这个问题。这些字段带有@Inject 注释

@Component
interface A {
    void run();
}

class B {
    @Inject
    A a;

    void someMethod() {
        a.run();
    }}

class C{
    @Inject
    B b;

    void anotherMethod() {
        b.someMethod();
    }
}

class CTest {
    @Mock
    B b;
    // remains null when invoked in the actual class though its mocked instance is
    // present here

    @Mock
    A a;
    //// remains null when invoked in the actual class though its mocked instance
    //// is present here

    @InjectMocks
    C c;

    @Before
    public void initialize() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void test() {
        c.anotherMethod();
    }

}

那么如何在使用 Mockito 向字段注入 @Inject 的实际类中获取模拟值?

【问题讨论】:

    标签: java unit-testing junit mockito inject


    【解决方案1】:

    我的猜测是,您应该使用 @RunWith(MockitoJUnitRunner.class) 注释您的 CTest 类并删除您的 before-method,因为它将变得不必要(@RunWith 将起到注入模拟的作用)。

    更新

    实际上,我在 IDE 中运行了您的代码。一切都很好,没有NPE。可能您必须检查您的导入是否正确。这是我的与你的比较:

    import org.junit.Before;
    import org.junit.Test;
    import org.mockito.InjectMocks;
    import org.mockito.Mock;
    import org.mockito.MockitoAnnotations;
    import javax.inject.Inject;
    import org.springframework.stereotype.Component;
    

    另外,请注意您在问题中使用大写字母(应为class C)声明了Class C,因此这段代码将无法编译。

    【讨论】:

    • 您好,感谢您的回答,此代码仅作为示例,并非我的实际代码。建议使用@RunWith(MockitoJUnitRunner.class) 或 MockitoAnnotations.initMocks(this) - 参考stackoverflow.com/a/28969255/2340345
    猜你喜欢
    • 1970-01-01
    • 2011-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-25
    • 1970-01-01
    • 2011-11-30
    • 1970-01-01
    相关资源
    最近更新 更多