Static Import in REST Assured

Profile picture for user arilio666

Static imports can be used in REST Assured to simplify code by giving direct access to static methods and fields of a class without explicitly specifying the class name. Static imports are often used in REST Assured to increase test script readability and conciseness.

You must import the static methods or fields from the respective classes to use static imports in REST Assured.

Example:

import static java.lang.System.out;
import static java.lang.Math.*;
class Test
{
      public static void main(String args[])
      {
             double example_1= sqrt(40);
             out.println("Square of 5 is:"+example_1);
    
             double example_2= tan(33);
             out.println("Tan of 30 is:"+example_2);
       }
}

Here is a basic example of how static import works. Because of static import, the print statement and the math function are used without class names.

REST Assured Example:

import static io.restassured.RestAssured;
import org.testng.annotations.Test;
public class MyRestAssuredTest {
  @Test
  public void testGet() {
     get( path: "https://reqres.in/api/users?page=2");
  }
}

Above code, we created a get method with a path without using the class name. Rest assured by importing a static method.

import static io.restassured.RestAssured.*;
import static io.restassured.matcher.RestAssuredMatchers.*;
import static org.hamcrest.Matchers.*;
public class ExampleTest {
   @Test
   public void exampleRestTest() {
     
       given()
           .param("id", 123)
       .when()
           .get("/users")
       .then()
           .statusCode(200)
           .body("name", equalTo("Luffy"))
           .body("age", greaterThan(18));
   }
}

The static import statements allow us to use methods such as provided(), when(), get(), then(), and matches such as equalTo() and greater-than () without explicitly referencing the class names.

Conclusion:

Static imports make the code more legible and expressive. To avoid confusion and potential conflicts with other imported static members, use static imports sparingly and only import the appropriate methods or fields. Remember to include the REST Assured dependencies in your project settings to utilize the static imports properly.