如何将RestAssured请求和响应信息记录到ExtentReports日志中

时间:2017-10-06 13:51:21

标签: log4j2 rest-assured extent extentreports

我有基于Rest Assured-TestNG的自动化套件,它使用范围报告。 我需要一种方法来使来自Rest Assured的所有日志也被记录到范围报告中。

我正在使用log4j将Rest Assured请求和响应记录到文件和控制台中,这些日志是否可以输入到扩展报告中?

有什么办法吗?

1 个答案:

答案 0 :(得分:0)

下面的示例代码将生成“范围报告”并记录详细信息。请不要,您还需要以下依赖项才能成功执行。

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.4</version>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.14.3</version>
</dependency>
<dependency>
<groupId>com.relevantcodes</groupId>
<artifactId>extentreports</artifactId>
<version>2.41.2</version>
</dependency>

<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<version>3.0.6</version>
</dependency>

确保上述依赖项已在pom中更新

import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.io.StringWriter;

import org.apache.commons.io.output.WriterOutputStream;
import org.testng.ITestContext;
import org.testng.ITestResult;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Test;

import com.relevantcodes.extentreports.ExtentReports;
import com.relevantcodes.extentreports.ExtentTest;
import com.relevantcodes.extentreports.LogStatus;

import io.restassured.RestAssured;
import io.restassured.filter.log.RequestLoggingFilter;
import io.restassured.response.Response;

/**
 * @author vamsir
 *
 */

public class SampleExtentReport {

    static StringWriter requestWriter;
    static PrintStream requestCapture;
    static ExtentTest test;
    static ExtentReports extentReports;

    @BeforeSuite
    public void init(ITestContext context) {


        extentReports = new ExtentReports(System.getProperty("user.dir") + File.separator + "reports" + File.separator
                +this.getClass().getSimpleName().toString() + ".html");

    }



    @Test
    public static void sampleTest() {

        test = extentReports.startTest("Get Sample Test");

        requestWriter = new StringWriter();
        requestCapture = new PrintStream(new WriterOutputStream(requestWriter));

        Response response = RestAssured.given().filter(new RequestLoggingFilter(requestCapture)).and().baseUri("https://jsonplaceholder.typicode.com").and().basePath("/todos/1").when().get();

        test.log(LogStatus.INFO, "Request : "+ requestWriter.toString());
        test.log(LogStatus.INFO, "Response : " + response.asString());

        extentReports.endTest(test);

    }


    @AfterMethod
    public void getResult(ITestResult result) throws IOException {
        if (result.getStatus() == ITestResult.FAILURE) {
            test.log(LogStatus.FAIL, result.getThrowable());
        }
    }

    @AfterSuite
    public void end() {

        extentReports.flush();
        extentReports.close();

    }

}