Reputation: 41
I have Filter class that extends OncePerRequestFilter. This filter is used for capturing audit data and then pass on to an async method for persisting in db. I need to write test cases for this entire scenario. How to achieve this? I don't have any great expertise on Junit.
public class AuditFilter extends OncePerRequestFilter {
private static final Logger LOGGER = LoggerFactory.getLogger(AuditFilter.class);
private AuditLogManager auditLogManager;
private String auditMode;
private List<String> urlPatterns;
/**
* @param auditLogManager - processes the audit logs.
* @param auditMode - modes of auditing (OFF,BASIC,DETAILED).
* @param urlPatterns - the URL patterns for which auditing to be done.
*/
public AuditFilter(final AuditLogManager auditLogManager, final String auditMode,
final List<String> urlPatterns) {
this.auditLogManager = auditLogManager;
this.auditMode = auditMode;
this.urlPatterns = urlPatterns;
}
@Override()
protected void doFilterInternal(final HttpServletRequest request,
final HttpServletResponse response, final FilterChain filterChain)
throws ServletException, IOException {
//capture audit data from request
try {
filterChain.doFilter(wrappedRequest, wrappedResponse);
} finally {
//capture audit data from response
// Executing asynchronous call. auditLogManager uses @Async annotation. Need i=integration test for auditLogManager code also
auditLogManager.log(auditInfo, auditMode);
}
}
}
I need to unit test every action performed by AuditFilter and AuditLogManager(class having asynchronous method) during maven build.
Upvotes: 4
Views: 4856
Reputation: 1471
This might be a late response. But an alternate approach that can be used.
With current spring 2.5.5, one option is to use RestTemplate approach
// use below annotation at class level
// the WebEnvironment with Random_port, this is required for test case
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
@Test
void postTest() {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
String bodyContent = "{\"appAPI\":\"<SOME-API-CODE-or-USER-NAME>\"}";
HttpEntity<String> requestEntity = new HttpEntity<>(bodyContent, headers);
//END POINT exposed in myapp, which will be used to provide the token.
String token = restTemplate
.postForObject("/myapp/authenticate",requestEntity, String.class);
ObjectMapper mapper = new ObjectMapper();
JsonNode root;
try {
root = mapper.readTree(token);
JsonNode tokenVal = root.path("jwtToken");
System.out.println("TKN: "+tokenVal.asText());
Assert.isTrue(tokenVal.asText()!=null, "Token received successfully");
} catch (JsonProcessingException e) {
Assert.isTrue(false,"Exception occurred: "+e.getMessage());
}
}
Upvotes: 1