如何在Mockito中模拟注入的bean?

时间:2019-03-26 12:28:06

标签: java java-ee junit mockito ejb

此测试有效:

@RunWith(MockitoJUnitRunner.class)
public class Test1 {

    @InjectMocks private MyBean bean;       

    @Test
    public void shouldWork() {      
        bean.test("ABC");       
    }
}

@Stateless
public class MyBean {

    public String test(String s) {
        System.out.println("This is a test " + s);
        return s;
    }
}

现在,我想在MyBean中注入新的EJB MyBean2并重新测试。为此,我也在Test1中模拟MyBean2。这是新测试:

@RunWith(MockitoJUnitRunner.class)
public class Test1 {

    @Mock MyBean2 bean2;        
    @InjectMocks MyBean bean;       

    @Test
    public void shouldWork() {
         bean.test("ABC");      
    }

}


@Stateless
public class MyBean {

    @Inject
    MyBean2 bean2;

    public String test(String s) {
        return s + bean2.test2();
    }
}


@Stateless
public class MyBean2 {
    public String test2() {
        return "DEF";
    }
}

但是当我运行此命令时,当bean尝试调​​用bean2方法时,我得到NullPointerException,可能是因为Mockito不能将注入的bean识别为EJB。

如何进行这项工作?

1 个答案:

答案 0 :(得分:2)

看看Javadoc of @InjectMocks。它指出您必须通过调用案例来调用正在使用的模拟的初始化:

@RunWith(MockitoJUnitRunner.class)
public class Test1 {
    @InjectMocks
    MyBean bean;
    @Mock
    MyBean2 bean2;

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

    @Test
    public void shouldWork() {
        when(bean2.test2()).thenReturn("mocked return");
        assertThat(bean.test("ABC")).isEqualTo("ABCmocked return");
    }
}