RestAssured : Redirect console logging to a file or a string object

 

RestAssured has rich features to be explored and customised.  

One of the things we can customize is logs.

If you would want to capture the request body along with headers and the response body which definitely helps in case of failure analysis of test here is a simple approach.

The RequestLoggingFilter & ResponseLoggingFilter  allows you to specify a default java.io.PrintStream that is used for logging when calling e.g. log().all().

You could choose to log just the Request / Response or both.

If you do not specify a PrintStream explicitly then RestAssured will default to the PrintStream defined by System.out, i.e. it will print the logs to the console.


 Let us look into how we can change this to write a file or a String Object instead:

File f = new File(".//src//test//resources//temp.txt");
PrintStream printStream = null; try {
printStream = new PrintStream(f);
} catch (FileNotFoundException e) {
e.printStackTrace();
} RequestLoggingFilter requestLogFilter = new RequestLoggingFilter(printStream);
ResponseLoggingFilter responseLogFilter = new ResponseLoggingFilter(printStream); Response response = request.filters(requestLogFilter, responseLogFilter)
.post("ENDPOINT_UNDERTEST");
response.then().log().all();
 final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        final String utf8 = StandardCharsets.UTF_8.name();
        PrintStream printStream = new PrintStream(baos, true, utf8);

        RequestSpecification request = RestAssured.given().filter(new RequestLoggingFilter(printStream))
                .filter(new ResponseLoggingFilter(printStream));

        Response response = request.post("ENDPOINT_UNDERTEST");
        response.then().assertThat().statusCode(200).and().contentType(ContentType.JSON).log().ifValidationFails();
        String data = baos.toString(utf8);

Comments

Popular posts from this blog

Benefits of Customised Assertions

How to setup Jenkins on Minikube