黄瓜\保证放心:如何获取请求规格?

时间:2019-06-23 09:28:08

标签: cucumber rest-assured

我执行以下步骤:

@Given("Request specifications are set with base uri {string}")
public void setRequestsSpec(String baseUri){

    requestSpecification = new RequestSpecBuilder()
            .setBaseUri(baseUri)
            .addFilter(new ResponseLoggingFilter())//log request and response for better debugging. You can also only log if a requests fails.
            .addFilter(new RequestLoggingFilter())
            .addFilter(new RcAllureFilter())
            .build();

那我有:

@When("^Azure Login Request Executed$")
public void azureLoginExecuted() {

    response =
    given()  //Add x-www-form-urlencoded body params:
        .spec(testContext().getRequestSpec())
        .formParam(GRANT_TYPE_KEY, GRANT_TYPE_VALUE)
        .formParam(AUTO_TEAM_CLIENT_ID_KEY, AUTO_TEAM_CLIENT_ID_VALUE)
        .formParam(AUTO_TEAM_CLIENT_SECRET_KEY, AUTO_TEAM_CLIENT_SECRET_VALUE)
        .formParam(RESOURCE_KEY, RESOURCE_VALUE)
    .when()
        .post(AUTO_TEAM_TENANT_ID + RESOURCE); //Send the request along with the resource

    setAuthorizationToken();
}

如何从中提取请求的详细信息,如URI,标头和参数? 我找不到可以从中提取请求详细信息的类。 在RequestSpecification类中,我几乎找不到此类中的任何getter函数。 我需要此值才能生成格式化的日志消息。 还有另一种方法吗?

谢谢。

1 个答案:

答案 0 :(得分:1)

如果您尝试从requestspecification中获取详细信息,则可以这样使用。

RequestSpecification spec = new RequestSpecBuilder().setContentType(ContentType.JSON).addHeader("h1", "h2")
                .build();
        QueryableRequestSpecification queryable = SpecificationQuerier.query(spec);

        System.out.println(" Content is  " + queryable.getContentType());
        System.out.println(" Header is  " + queryable.getHeaders().getValue("h1"));

但是在您的情况下,您也需要请求详细信息。因此,最好的方法是使用一个requestlogging过滤器,该过滤器接受一个PrintStream(这反过来可以与ByteArrayOutPutStream一起使用,后者可以转换为String)。基本思想是,将RequestLoggingFilter与PRintStream一起使用,然后使用任何代码将PrintStream保存到String。您也可以使用usr StringWriter。

RequestSpecification spec = new RequestSpecBuilder().build();
    StringWriter requestWriter = new StringWriter();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PrintStream printStream = new PrintStream(baos);

    Response response = given().spec(spec).contentType(ContentType.JSON)
            .filter(new RequestLoggingFilter(printStream)).get("https://jsonplaceholder.typicode.com/todos/1");
    printStream.flush();
    System.out.println(baos);