java—如何向注入的类成员提供模拟示例

hjzp0vay  于 2021-07-09  发布在  Java
关注(0)|答案(1)|浏览(388)

我正在使用JUnit4和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仍然存在。
如何才能做到这一点?

pvcm50d1

pvcm50d11#

@injectmocks注解应该放在要测试的对象示例上。

@Mock
ConfigService mockedConfigService;

@InjectMocks
FeedbackServlet tested = new FeedbackServlet();

相关问题