user7532276
user7532276

Reputation:

Rest Assured - body() in given() or when()

What differences putting .body() in given() or when()? I tried both and they works the same.

The documentation on rest-assured git page says .body() is inserted in given(), and I tried searching for any article on putting .body() in when(), but found nothing. I asked because the team I'm working with is using body() in when().

Code Example:

// #1  
given().headers("Content-Type", "application/json").body(classBody).
when().post(urlAPI).
then().contentType(ContentType.JSON).extract().response()

// #2
given().headers("Content-Type", "application/json").
when().body(classBody).post(urlAPI).
then().contentType(ContentType.JSON).extract().response()

Both codes return the same result. So, which one is better?

Upvotes: 2

Views: 7245

Answers (3)

Mad Xeme
Mad Xeme

Reputation: 1

This is the best way to write the code. Given(), when() is used to make the code more readable and understandable. That are called as syntactic sugar.

given().headers("Content-Type", "application/json").body(classBody).when().post(urlAPI)
.then().contentType(ContentType.JSON).extract().response()

Upvotes: -1

Thanh Chuong
Thanh Chuong

Reputation: 21

  1. Given and When work as the same
  2. They used to make the test more readable. So, depend on your purpose you can use them interchangeable

Upvotes: 2

baadnews
baadnews

Reputation: 128

If you take a look at the java docs you will notice that when() is a syntactic sugar. So basically it will only affect the look of your code, you could skip when() and it will work.

I prefer to use example #1.

Upvotes: 3

Related Questions