Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue after moving the RequestSpecification code under @BeforeClass

Below code works fine for me:

    @Test (priority=1, dependsOnMethods = {"checkIfAllServicesAreUp"})
    public void verifyCreateUser() {
        RestAssured.baseURI = "someValidURI";
        RestAssured.basePath = "userservice/user/";
        RequestSpecification spec = new RequestSpecBuilder().setContentType(ContentType.JSON).log(LogDetail.METHOD).build();
        response = RestAssured.given().spec(spec).headers("source","APP").body("{ }").when().post("");
    }

But when I move the RequestSpecification related code under @BeforeClass in below manner:

    private RequestSpecification spec;

    @BeforeClass
    public void setSpec() {
        spec = new RequestSpecBuilder().setContentType(ContentType.JSON).log(LogDetail.METHOD).build();
    }

    @Test (priority=1, dependsOnMethods = {"checkIfAllServicesAreUp"})
    public void verifyCreateUser() {
        RestAssured.baseURI = "someValidURI";
        RestAssured.basePath = "userservice/user/";
        response = RestAssured.given().spec(spec).headers("source","APP").body("{ }").when().post("");
    }

My API test returns error code 405 (Method not allowed).

It seems spec is overriding the RestAssured.basePath assignment inside my test method verifyCreateUser since I'm not setting the same in spec explicitly, and the POST call is getting hit at someValidURI instead of someValidURI+/userservice/user, and hence the 405 error code. I do not want to set the basePath in spec since it would be different for each of my test methods. Please help find an elegant solution here.

like image 748
Akshay Maldhure Avatar asked Feb 05 '26 16:02

Akshay Maldhure


1 Answers

Modified my code as mentioned below and it's working fine now:

@Test (priority=1, dependsOnMethods = {"checkIfAllServicesAreUp"})
public void verifyCreateUser() {
    RestAssured.baseURI = "someValidURI";
    RequestSpecification spec = new RequestSpecBuilder().setBasePath("userservice/user/").setContentType(ContentType.JSON).log(LogDetail.METHOD).build();
    response = RestAssured.given().spec(spec).headers("source","APP").body("{ }").when().post("");
}

Apparently, the way I was configuring the basePath per test was incorrect earlier. I now do it within spec.

Hope this helps someone in future.

like image 168
Akshay Maldhure Avatar answered Feb 09 '26 09:02

Akshay Maldhure