此测试有效:
@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。
如何做到这一点?
看看 @InjectMocks
的 Javadoc 。它指出,您必须通过调用您的案例来调用正在使用的模拟的初始化:
@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");
}
}