Reputation: 1905
I am creating unit tests using JUnit 4 and mockito. I encountered a problem when trying to provide a mock instance for one of the class members.
Here's the class to be tested:
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);
}
}
When I try to use configService.send(feedbackData)
, the test produces a NullPointerException
. Now I tried to Inject the missing value in the test class:
public class FeedbackServletTest extends Mockito {
@InjectMocks
private ConfigService configService = mock(ConfigService.class);
@Test
public void testDoPost() throws Exception {
...
when(configService.send(new FeedbackData("Nikola", "[email protected]", "Our virtues and our failings are inseparable, like force and matter." +
"When they separate, man is no more.", "09991234567"))).thenCallRealMethod();
...
}
}
I tried to re-run the tests but the NPE is still there.
How can this be done properly?
Upvotes: 0
Views: 1507
Reputation: 1608
@InjectMocks annotation should be placed on an object instance You want to test.
@Mock
ConfigService mockedConfigService;
@InjectMocks
FeedbackServlet tested = new FeedbackServlet();
Upvotes: 1