简体   繁体   中英

How to configure RestAssured LogConfig to write request and response to a text file

I am totally newbie to RestAssured. I like to write the request and response to text file. I do not want to repeat code in each and every test to extract and write Request and Response but instead I like to configure RestAssuredConfig in a setup method to redirect the request and response to text file.

Can someone please help me understand what I am missing in my code? I am trying to configure LogConfig to write request and response to StringWriter so that I can use it to write to a required file?

I tried several examples from google but none helped.

Please note, below example is a proto type in which I am temporarily doing sysout and once the code works I can write it to text file.

//This is a sample code from where I am calling the configure log method //configureRequestLogging

RequestSpecification request = given();
RequestSpecification logRequest = configureRequestLogging(request);

//This method is expected to SOP the request and response. But I am always getting void

private static RequestSpecification configureRequestLogging(RequestSpecification request) {
    RequestSpecification requestSpec;
    final StringWriter writer = new StringWriter();
    PrintStream captor = new PrintStream(new WriterOutputStream(writer), true);
    requestSpec = request.config(RestAssuredConfig.config().logConfig(LogConfig.logConfig().defaultStream(captor)))
    .log().all();

    System.out.println(writer.toString());

    return requestSpec;
    }

You may create a new logging filter (interface Filter ) if you want to have file output separated from console output (eg provide more details) There you can specify print stream

@Override
public Response filter(FilterableRequestSpecification requestSpec, FilterableResponseSpecification responseSpec, FilterContext ctx) {
    RequestPrinter.print(requestSpec, requestSpec.getMethod(), requestSpec.getUri(), LogDetail.ALL, new PrintStream(new FileOutputStream("example.txt", true)), true);
    return ctx.next(requestSpec, responseSpec);
}

Also you just could add built-in RequestLoggingFilter with required print stream.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM