如何向注入的类成员提供模拟实例

时间:2017-10-31 13:30:46

标签: java unit-testing junit mockito

我正在使用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仍在那里。

如何正确完成?

1 个答案:

答案 0 :(得分:1)

@InjectMocks注释应放在您想要测试的对象实例上。

@Mock
ConfigService mockedConfigService;

@InjectMocks
FeedbackServlet tested = new FeedbackServlet();