我需要从每个 Rest Assured 测试中获取“CURL”操作,并在未通过测​​试时在控制台中打印。这是可能的?

例如,转换:

 given().relaxedHTTPSValidation().
   auth().basic("name", "password").
   param("grant_type","client_credentials").
 when().
   post("https://test_url/oauth/token").
 then().
   statusCode(200);


curl --user name:passwoed -k -X POST \
https://test_url/oauth/token \
-H 'cache-control: no-cache' \
-H 'content-type: application/x-www-form-urlencoded' \
-d grant_type=client_credentials

最佳答案

包括以下依赖项。

马文:

<dependency>
  <groupId>com.github.dzieciou.testing</groupId>
  <artifactId>curl-logger</artifactId>
  <version>1.0.4</version>
</dependency>
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>1.6.6</version>
</dependency>
<dependency>
    <groupId>ch.qos.logback</groupId>
    <artifactId>logback-classic</artifactId>
    <version>1.0.9</version>
</dependency>

配置完成后,使用以下代码在控制台输出中记录 curl 请求。
package com.api.test;

import static org.hamcrest.CoreMatchers.is;

import org.json.JSONObject;
import org.testng.annotations.Test;

import com.sample.model.EnrollEmail;
import com.github.dzieciou.testing.curl.CurlLoggingRestAssuredConfigFactory;

import io.restassured.RestAssured;
import io.restassured.config.RestAssuredConfig;
import io.restassured.http.ContentType;
import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;
import io.restassured.response.ValidatableResponse;

/**
 * @author vamsiravi
 *
 */
public class Sample {

    @Test(enabled=true)
    public void sampleAPITest() {

        RestAssuredConfig config = CurlLoggingRestAssuredConfigFactory.createConfig();

        EnrollEmail email = new EnrollEmail();
        email.setEmailAddress("[email protected]");
        RestAssured.given().config(config).contentType(ContentType.JSON).body(email).when().post("https://jsonplaceholder.typicode.com/posts").then()
        .assertThat()
        .statusCode(201);

    }
}

输出 :
[main] DEBUG curl - **
curl 'https://jsonplaceholder.typicode.com/posts'
-H 'Accept: */*'
-H 'Content-Type: application/json; charset=UTF-8'
-H 'Host: jsonplaceholder.typicode.com'
-H 'Connection: Keep-Alive'
-H 'User-Agent: Apache-HttpClient/4.5.3 (Java/1.8.0_181)'
--data-binary '{"emailAddress":"[email protected]"}'
--compressed
-k
-v**

PASSED: sampleAPITest

10-08 10:57