RestAssured #10 - Automating POST Request (User Registration API) - Part 2

Introduction

In this article, we are going to see the below concepts with examples -

  1. Response Header validation

  2. How to enable logs for request and response

Response Header validation

Headers are name and value pairs. To validate the header in Rest Assured we can use getHeader() which is declared in the ResponseOptions interface

String getHeader(String name) // where name is the key of the response header and it returns header value associated with the given name

Below are other methods available for getting a response header

  • String header(String name)

  • Headers headers() -The response headers. If there are several response headers with the same name a list of the response header values is returned.

  • Headers getHeaders() - If there are several response headers with the same name a list of the response header values is returned.

How to enable logs for request and response

Certain times we need to print request and response details for debugging or logging purposes to check what was requested and what response was received. RestAssured provides below 2 interfaces where methods are defined for logging request and response

  • LogSpecification interface is having method like body(), all(), headers() to print request details

  • ValidatableResponseLogSpec interface has methods like status(), body(), all(), and headers() to print response details.

We are going to see examples for the above 2 in the below sections.

User Registration with All Fields Test case

Test Case ID: UR002

Test Case Summary: User Registration API with all fields and validate response header and body

Test Objective: Verify that the user registration API creates a new user account with all fields and returns a successful response with user-created details.

Test Steps:

  1. Prepare the test data

    1. Create a test user with a valid username, first_name, last_name, email and password.
  2. Send a POST request to the user registration API with the test data as the request body

  3. Verify that the API returns a successful response with a 201 HTTP status code.

  4. Verify response header has Content-Type, Content-Length field

  5. Verify that the response contains a unique identifier for the new username, first_name, last_name and email and it doesn't contain a password field.

Test Data:

HTTP Method - POST

Endpoint - https://test-api.k6.io/user/register/

Header - Content-Type: application/json

Request Payload - The request should contain all fields and the username should be unique

{
    "username": "TestUser2023020720401211",
    "first_name": "TestUser",
    "last_name": "2023020720401212",
    "email": "TestUser2023020720401212@tester.com",
    "password": "1"
}

Request Example

Expected Results:

The response should have: Status Code - 201

Response Header - It should have Content-Type=" application/json", Content-Length > 0

Response Body - It should contain the username, first_name, last_name and email and have the same value we have passed in the request body

{
    "username": "TestUser2023020720401211",
    "first_name": "TestUser",
    "last_name": "2023020720401212",
    "email": "TestUser2023020720401212@tester.com"
}

Response Example

Header

Body

Example

Validating response header

public String getResponseHeaderUsingKey(String key){
    return response.getHeader(key);
}

Logging requests and response in the console

public void createUser(){
    response = RestAssured.given()
            .contentType(ContentType.JSON)
            .body(userRegistrationRequestBody)
            .log().body()
            .post(userRegisterPath);

    response.then().log().body();
}

UserRegistration.java

public class UserRegistration {

    private final String baseUri = "https://test-api.k6.io";
    private final String userRegisterPath = "/user/register/";

    private String userRegistrationRequestBody;
    private Response response;

    public UserRegistration(String userName, String password){
        RestAssured.baseURI = baseUri;
        userRegistrationRequestBody = "{\"username\": \""+userName+"\",\"password\": \""+password+"\"}";
    }
    public UserRegistration(String userName, String password,String firstName, String lastName,String email){
        RestAssured.baseURI = baseUri;
        userRegistrationRequestBody = "{\"username\": \""+userName+"\",\"password\": \""+password+"\",\"first_name\":\""+firstName+"\",\"last_name\":\""+lastName+"\",\"email\":\""+email+"\"}";
    }

    public void createUser(){
        response = RestAssured.given()
                .contentType(ContentType.JSON)
                .body(userRegistrationRequestBody)
                .log().body()
                .post(userRegisterPath);

        response.then().log().body();
    }

    public int getStatusCode(){
        return response.getStatusCode();
    }

    public String getResponseBodyUsingKey(String key){
        JsonPath jsonPath = response.jsonPath();
        return jsonPath.getString(key);
    }

    public String getResponseHeaderUsingKey(String key){
        return response.getHeader(key);
    }
}

Test

@Test
public void userRegistrationWithAllFieldsTest(){
    String dateTime = DateFormatUtils.getTimeStamp("yyyyMMddHHmmss");
    int fourDigitRandom = RandomNumberUtils.getRandomNumber(4);

    String password = "1";
    String firstName = "TestUser";
    String lastName =  dateTime+fourDigitRandom;
    String userName = firstName+lastName;
    String email = userName+"@tester.com";

    UserRegistration userRegistration = new UserRegistration(userName,password,firstName,lastName,email);
    userRegistration.createUser();

    Assert.assertEquals(userRegistration.getStatusCode(),201);
    // Validate response header
    Assert.assertEquals(userRegistration.getResponseHeaderUsingKey("Content-Type"),"application/json");
    assert Integer.parseInt(userRegistration.getResponseHeaderUsingKey("Content-Length")) > 0;
    //Validate response body
    Assert.assertEquals(userRegistration.getResponseBodyUsingKey("username"),userName);
    Assert.assertEquals(userRegistration.getResponseBodyUsingKey("first_name"),firstName);
    Assert.assertEquals(userRegistration.getResponseBodyUsingKey("last_name"),lastName);
    Assert.assertEquals(userRegistration.getResponseBodyUsingKey("email"),email);
}

Validate Login

Test Case ID: UR003

Test Case Summary: Validate that user is able to log in for new account created

Test Objective: Validate that the new user account created is able to log in.

Test Steps:

  1. Prepare the test data

    1. Create a new user with a valid username, first_name, last_name, email and password using the user registration API.
  2. Send a POST request to the login API with the test data as the request body

  3. Verify that the API returns a successful response with a 200 HTTP status code.

  4. Verify that the response contains an id, username, first_name, last_name, email, and date joined and it doesn't contain a password field.

Test Data:

HTTP Method - POST

Endpoint - https://test-api.k6.io/auth/basic/login/

Header - Content-Type:application/json

Request Payload - The request should valid username and password.

{
    "username": "TestUser2023020720401211",
    "password": "1"
}

Request Example

Expected Results:

The response should have: Status Code - 200

Response Body - It should contain the username, first_name, last_name and email and have the same value we have passed in the request body while creating the account

{
    "id": 674770,
    "username": "TestUser2023020720401211",
    "first_name": "TestUser",
    "last_name": "2023020720401212",
    "email": "TestUser2023020720401212@tester.com",
    "date_joined": "2023-02-12T12:39:06.903923Z"
}

Response Example

Example

Login.java

public class Login {
    private final String baseUri = "https://test-api.k6.io";
    private final String loginPath = "/auth/basic/login/";

    private String loginRequestBody;
    private Response response;

    public Login(String userName, String password){
        RestAssured.baseURI = baseUri;
        loginRequestBody = "{\"username\": \""+userName+"\",\"password\": \""+password+"\"}";
    }
    public void performLogin(){
        response = RestAssured.given()
                .contentType(ContentType.JSON)
                .body(loginRequestBody)
                .log().body()
                .post(loginPath);

        response.then().log().body();
    }

    public int getStatusCode(){
        return response.getStatusCode();
    }

    public String getResponseBodyUsingKey(String key){
        JsonPath jsonPath = response.jsonPath();
        return jsonPath.getString(key);
    }

    public String getResponseHeaderUsingKey(String key){
        return response.getHeader(key);
    }
}

Test

@Test
public void validateLoginForNewAccountTest() throws InterruptedException {
    String dateTime = DateFormatUtils.getTimeStamp("yyyyMMddHHmmss");
    int fourDigitRandom = RandomNumberUtils.getRandomNumber(4);

    String password = "1";
    String firstName = "TestUser";
    String lastName = dateTime + fourDigitRandom;
    String userName = firstName + lastName;
    String email = userName + "@tester.com";

    UserRegistration userRegistration = new UserRegistration(userName, password, firstName, lastName, email);
    userRegistration.createUser();

    Login login = new Login(userName,password);
    login.performLogin();

    Assert.assertEquals(login.getStatusCode(),200);

    Assert.assertEquals(login.getResponseBodyUsingKey("username"),userName);
    Assert.assertEquals(login.getResponseBodyUsingKey("first_name"),firstName);
    Assert.assertEquals(login.getResponseBodyUsingKey("last_name"),lastName);
    Assert.assertEquals(login.getResponseBodyUsingKey("email"),email);
}

User Registration with duplicate username and email Test case

Test Case ID: UR003

Test Case Summary: User Registration API with a duplicate username.

Test Objective: Verify that the user registration API returns an error when the existing username and email are used in the request.

Test Steps:

  1. Prepare the test data

    1. Create a test user with a duplicate username and email.
  2. Send a POST request to the user registration API with the test data as the request body

  3. Verify that the API returns an error response with a 400 HTTP status code(Bad Request)

  4. Verify that the response contains an error message for username and email.

Test Data:

HTTP Method - POST

Endpoint - https://test-api.k6.io/user/register/

Header - Content-Type:application/json

Request Payload - The request should contain all fields and the username & email should be duplicated.

{
    "username": "TestUser2023020720401211",
    "first_name": "TestUser",
    "last_name": "2023020720401212",
    "email": "TestUser2023020720401212@tester.com",
    "password": "1"
}

Expected Results:

The response should have: Status Code - 400

Response Body - It should contain an error message for the username and email field.

{
    "username": [
        "A user with that username already exists."
    ],
    "email": [
        "User with this email already exists!"
    ]
}

Example

Test

@Test
public void validateDuplicateUserNameIsNotAllowedForUserRegistration() {
    String dateTime = DateFormatUtils.getTimeStamp("yyyyMMddHHmmss");
    int fourDigitRandom = RandomNumberUtils.getRandomNumber(4);

    String password = "1";
    String firstName = "TestUser";
    String lastName = dateTime + fourDigitRandom;
    String userName = firstName + lastName;
    String email = userName + "@tester.com";

    String duplicateUserMessage = "[A user with that username already exists.]";
    String duplicateEmailMessage = "[User with this email already exists!]";

    UserRegistration userRegistration = new UserRegistration(userName, password, firstName, lastName, email);
    userRegistration.createUser();

    UserRegistration duplicateUserRegistration = new UserRegistration(userName, password, firstName, lastName, email);
    duplicateUserRegistration.createUser();

    Assert.assertEquals(duplicateUserRegistration.getStatusCode(),400);

    Assert.assertEquals(duplicateUserRegistration.getResponseBodyUsingKey("username"),duplicateUserMessage);
    Assert.assertEquals(duplicateUserRegistration.getResponseBodyUsingKey("email"),duplicateEmailMessage);
}

Git Hub Repo Link - https://github.com/sksingh329/RestAssuredTutorials

Did you find this article valuable?

Support SUBODH SINGH by becoming a sponsor. Any amount is appreciated!