Sobhit Sharma
Sobhit Sharma

Reputation: 713

How to create query param body with multiple key param values

In the below hashmap you can see, I have list of key param values for which I need to automate cases for multiple values without repeating the hashmap rather it would be and update.

How I am doing it:

1st test case

HashMap<String, String> queryParam = new HashMap<>();
queryParam.put("Name", Name);
queryParam.put("street","street" );
queryParam.put("city","city" );
queryParam.put("state", "state");
queryParam.put("postalCode","postalCode" );
queryParam.put("country", "country");
queryParam.put("email", "email");
queryParam.put("website","website" );
queryParam.put("phone", "phone");

Response response = request.auth().basic(uname, pwd).body(queryParam).contentType(APPLICATION_JSON)
            .post().then().extract()
            .response();

Now if you see the above hashmap, it has mandatory params, some optional and then each param has different validation. Now it terms to cover all the testcases with each keys, above haspmap is repeating and values or keys are changing. I would like to do this in better and efficient way of it.

Upvotes: 0

Views: 574

Answers (1)

lucas-nguyen-17
lucas-nguyen-17

Reputation: 5917

Instead of using Map<K, V>, you should use Java POJO. Using constructor to setup default value, then using setter to change value. It's more efficient.

One more thing, you could apply Factory design pattern to build object with desired value for each test case.

Test example

@Test
void test1() {
    QueryObject query = QueryObjectFactory.getDefaultValue();

    Response res = given().contentType(ContentType.JSON)
            .body(query)
            .post("to_your_api_endpoint");
}

Factory class

public class QueryObjectFactory {

    public static QueryObject getDefaultValue() {
        QueryObject queryObject = new QueryObject();
        queryObject.setName("name");
        queryObject.setStreet("street");
        queryObject.setCity("city");
        queryObject.setCountry("country");
        queryObject.setState("state");
        queryObject.setPostalCode("postalCode");
        queryObject.setEmail("email");
        queryObject.setWebsite("website");
        queryObject.setPhone("phone");
        return queryObject;
    }
}

POJO note: I use lombok to generate getter and getter --> reduce complex of POJO class.

import lombok.Data;

@Data
public class QueryObject {
    private String name;
    private String street;
    private String city;
    private String state;
    private String postalCode;
    private String country;
    private String email;
    private String website;
    private String phone;
}

Upvotes: 1

Related Questions