У меня есть простой фильтр, который обрабатывает ответ следующим образом.
public class CustomInjectFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// No implementation needed
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
try {
PrintWriter originalOutWriter = response.getWriter();
// Custom wrapper to get the response
CustomResponseWrapper responseWrapper = new CustomResponseWrapper((HttpServletResponse) response);
// Continue to process everything in the chain
filterChain.doFilter(request, responseWrapper);
// Add to the original response
StringWriter newWriter = new StringWriter();
String originalContent = responseWrapper.getResponseContent();
// Conver to json
Gson gson = new GsonBuilder().registerTypeAdapter(Pojo.class, new CustomDataSerializer()).create();
// At this point I do some custom stuff like adding few attributes to Pojo class before transforming it back to json.
newWriter.write(gson.toJson(str));
response.setContentLength(newWriter.toString().length());
originalOutWriter.write(newWriter.toString());
originalOutWriter.close();
} catch (Exception e) {
throw new IllegalArgumentException("Unable to serialize/deserialize data");
}
}
@Override
public void destroy() {
// No implementation needed
}
}
Регистрация его с помощью
@Configuration
public class CustomConfiguration {
@Bean
@Order(Ordered.HIGHEST_PRECEDENCE)
public FilterRegistrationBean custFilterRegistrationBean() {
CustomInjectFilter filter = new CustomInjectFilter();
FilterRegistrationBean bean = new FilterRegistrationBean();
bean.setFilter(filter);
List<String> match = new ArrayList<>();
match.add("**/setup/*");
bean.setUrlPatterns(match);
return bean;
}
}
Junit-тестов,
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = {TestConfiguration.class})
public class CustomInjectFilterITest {
@Test
public void testDoFilter() throws ServletException, IOException {
CustomInjectFilter filter = new CustomInjectFilter();
HttpServletRequest mockReq = Mockito.mock(HttpServletRequest.class);
HttpServletResponse mockResp = Mockito.mock(HttpServletResponse.class);
FilterChain mockFilterChain = Mockito.mock(FilterChain.class);
FilterConfig mockFilterConfig = Mockito.mock(FilterConfig.class);
Mockito.when(mockReq.getRequestURI()).thenReturn("/setup");
final StringWriter stringWriter = new StringWriter();
final PrintWriter writer = new PrintWriter(stringWriter);
writer.print("{\"source\":\"testdata\"}");
Mockito.when(mockResp.getWriter()).thenReturn(writer);
filter.init(mockFilterConfig);
filter.doFilter(mockReq, mockResp, mockFilterChain);
filter.destroy();
}
}
IЯ совершенно не уверен, правильно ли я написал этот тест, поскольку responseWrapper.getResponseContent()
всегда пуст.
Правильно ли я настроил этот модульный тест?