Search code examples
rest-assured

Defining Separate RestAssured.RequestSpecifications for admin/user endpoints


I have a setup where different authentications are present for lets say admins and users...

I had two different Test Classes which each their @BeforeAll setting the RequestSpecification for the @Tests in their respecive classes:

Admin


//...

  @BeforeAll
  public static void setupResponseSpecification() {
    requestSpec = new RequestSpecBuilder()
        .setBaseUri("https://admin.test.mysite.com")
        .setAccept("application/json")
        .addHeader("X-Client-Id", "admin-test")
        .build();

    responseSpec = new ResponseSpecBuilder()
        //.expectStatusCode(HttpStatus.SC_OK)
        .expectResponseTime(Matchers.lessThan(5L), TimeUnit.SECONDS)
        .expectContentType(ContentType.JSON)
        .build();

    RestAssured.requestSpecification = requestSpec;
    RestAssured.responseSpecification = responseSpec;
  }

//...

User


//...

  @BeforeAll
  public static void setupResponseSpecification() {
    requestSpec = new RequestSpecBuilder()
        .setBaseUri("https://user.test.mysite.com")
        .setAccept("application/json")
        .addHeader("X-Client-Id", "user-test")
        .build();

    responseSpec = new ResponseSpecBuilder()
        //.expectStatusCode(HttpStatus.SC_OK)
        .expectResponseTime(Matchers.lessThan(5L), TimeUnit.SECONDS)
        .expectContentType(ContentType.JSON)
        .build();

    RestAssured.requestSpecification = requestSpec;
    RestAssured.responseSpecification = responseSpec;
  }

//...

I kept getting 401 errors on one of the classes, but it worked when I uncommented the whole of the opposite class, leading me to the conclusion that the line RestAssured.requestSpecification = requestSpec; which was run last, was the one to be active for both.

Is it possible to define two Spec templates and set the appropriate one for each test?


Solution

  • requestSpecification and responseSpecification are static fields of RestAssured class. This is why you cannot have them different in case your tests are parallel.

    Having requestSpec saved in your @BeforeAll you can use it in your test with the construction like:

    RestAssured
            .given(requestSpec)
            .get()
            .then()
            .spec(responseSpec);