关联ID的单元测试doFilter

时间:2018-10-07 01:13:04

标签: java servlets correlation servlet-filters dropwizard

我正在使用dropwizard构建应用程序。

我做了一个过滤器来拦截和记录呼叫服务的相关ID。

如果传入请求的标头中没有标头“ Correlation-Id”,我们将在响应中附加一个。

以下是过滤器:

public class CorrelationIdServletFilter implements Filter {

private static final Logger LOGGER =
  LoggerFactory.getLogger(CorrelationIdServletFilter.class);

 private static final String CORRELATION_ID_HEADER_NAME = "Correlation-ID";

 private static final String CORRELATION_ID_MDC_KEY = " ";

 private static final InheritableThreadLocal<String> correlationId =
  new InheritableThreadLocal<>();

  public static String getCorrelationId() {
return correlationId.get();
 }

 @Override
 public void init(FilterConfig filterConfig) throws ServletException {}

 @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
  throws IOException, ServletException {

try {
  HttpServletRequest req = (HttpServletRequest) request;

  HttpServletResponse res = (HttpServletResponse) response;

  String correlationIdHeaderValue = req.getHeader(CORRELATION_ID_HEADER_NAME);

  LOGGER.debug
      (
      "HTTP Header("
          + CORRELATION_ID_HEADER_NAME
          + ") = ["
          + correlationIdHeaderValue
          + "] will generate a new correlationId if incoming is NULL");

  String correlationIdRaw;

  if (!StringUtils.isEmpty(correlationIdHeaderValue)) {
    correlationIdRaw = correlationIdHeaderValue;
  } else {
    correlationIdRaw = UUID.randomUUID().toString();
  }

  LOGGER.debug("Request: (" + req.getRequestURI() + ") is marked as :" + correlationIdRaw);

  correlationId.set(correlationIdRaw);

  MDC.put(CORRELATION_ID_MDC_KEY, getCorrelationId());

  res.addHeader(CORRELATION_ID_HEADER_NAME, correlationIdRaw);

  LOGGER.debug(
      "Response holds correlationId : ("
          + res.getHeader("Correlation-ID")
          + ") in its header ");

  chain.doFilter(req, res);

} finally {
  correlationId.remove();
  MDC.remove(CORRELATION_ID_MDC_KEY);
}
}

  @Override
  public void destroy() {}
}

我需要编写涉及两种情况的单元测试:

  1. 在发送没有相关ID的请求时。检查ID是在服务器端生成的。

  2. 发送带有相关ID的响应时。确认它是否已发送回响应。

谁能指出我该怎么做?

我尝试使用模拟,但我不是响应头中没有任何内容。

@Test
  public void testResponse_for_RequestWithoutCcid() throws IOException, ServletException {

HttpServletRequest httpServletRequest = mock(HttpServletRequest.class);
HttpServletResponse httpServletResponse = mock(HttpServletResponse.class);
FilterChain filterChain = mock(FilterChain.class);
CorrelationIdServletFilter CorrelationIdServletFilter = mock(
    CorrelationIdServletFilter.class);
CorrelationIdServletFilter.init(mock(FilterConfig.class));

CorrelationIdServletFilter.doFilter(httpServletRequest, httpServletResponse,
    filterChain);


System.out.println(httpServletResponse.getHeaderNames());

CorrelationIdServletFilter.destroy();

verify(CorrelationIdServletFilter, times(1))
    .doFilter(httpServletRequest, httpServletResponse, filterChain);

}

有什么办法可以做到这一点?任何帮助将非常感激。有没有模拟的方法吗?

1 个答案:

答案 0 :(得分:3)

您编写的测试中的一些主要问题:

  1. 永远不要模拟被测类(可能会有一些例外),因为您想对被测类的各种方法进行单元测试的实际调用。
  2. 我们应该始终为被测类的不同方法编写单独的单元测试。在这里,我可以看到您还调用了initdestroy方法,当您要测试doFilter方法时不需要。
  3. 创建任何模拟对象时,我们会使用期望值定义期望对模拟对象进行的调用,并在需要时让它们返回一些存根值。

现在,我尝试编写正确的测试,以断言要测试的两种情况:

@Test
public void testResponse_for_RequestWithoutCcid() throws IOException, ServletException {

HttpServletRequest httpServletRequest = mock(HttpServletRequest.class);
HttpServletResponse httpServletResponse = mock(HttpServletResponse.class);
FilterChain filterChain = mock(FilterChain.class);
CorrelationIdServletFilter correlationIdServletFilter = new CorrelationIdServletFilter();

expect(httpServletRequest.getHeader(CORRELATION_ID_HEADER_NAME)).andReturn(""); // Empty correlation id in the request

Capture capturedCorrelationIdRaw = newCapture();

httpServletResponse.addHeader(CORRELATION_ID_HEADER_NAME, capture(capturedCorrelationIdRaw));
expectLastCall(); // used for void methods in EasyMock framework

filterChain.doFilter(httpServletRequest, httpServletResponse);
expectLastCall();

CorrelationIdServletFilter.doFilter(httpServletRequest, httpServletResponse,
    filterChain);


assertNotEmpty(capturedCorrelationIdRaw.getValue());


verify(httpServletRequest, times(1))
    .getHeader(CORRELATION_ID_HEADER_NAME);
verify(httpServletResponse, times(1))
    .addHeader(CORRELATION_ID_HEADER_NAME, anyString);

}

此测试需要根据使用的实际测试框架进行更新,但我已尽力为您提供测试外观的想法。