我正在使用JUnit 4和mockito创建单元测试。尝试为其中一个类成员提供模拟实例时遇到问题。
下面是要测试的类:
public class FeedbackServlet extends SlingAllMethodsServlet {
@Reference
private ConfigService configService;
@Override
protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) {
FeedbackData feedbackData = extractFeedbackData(request.getRequestParameterMap());
try {
boolean isEmailSent = configService.send(feedbackData);
} catch (Exception e) {
...
}
}
private FeedbackData extractFeedbackData(RequestParameterMap data) {
String firstName = data.getValue(ParamKey.FIRST_NAME.toString()).getString();
String email = data.getValue(ParamKey.EMAIL.toString()).getString();
String message = data.getValue(ParamKey.MESSAGE.toString()).getString();
String contactNumber = data.getValue(ParamKey.CONTACT_NUMBER.toString()).getString();
return new FeedbackData(firstName, email, message, contactNumber);
}
}
当我尝试使用configService.send(feedbackData)
时,测试会产生一个NullPointerException
。现在我尝试在测试类中注入缺失值:
public class FeedbackServletTest extends Mockito {
@InjectMocks
private ConfigService configService = mock(ConfigService.class);
@Test
public void testDoPost() throws Exception {
...
when(configService.send(new FeedbackData("Nikola", "nikola.tesla@genius.co", "Our virtues and our failings are inseparable, like force and matter." +
"When they separate, man is no more.", "09991234567"))).thenCallRealMethod();
...
}
}
我试图重新运行测试,但 NPE 仍然存在。
如何正确完成此操作?
@InjectMocks注释应放置在要测试的对象实例上。
@Mock
ConfigService mockedConfigService;
@InjectMocks
FeedbackServlet tested = new FeedbackServlet();