Randomly changing the JSON Values for every "Post" Request Body using Java

1.3k views Asked by At

This could be a duplicate question, but I couldn't find my solution anywhere. Hence, posting it.

I am trying to simply POST a request for a Student account Creation Scenario. I do have a JSON file which comprises all the "Keys:Values", required for Student account creation.

This is how the file student_Profile.json looks like:

{
   "FirstName":"APi1-Stud-FN",
   "MiddleInitial":"Q",
   "LastName":"APi1-Stud-LN",
   "UserAlternateEmail":"",
   "SecretQuestionId":12,
   "SecretQuestionAnswer":"Scot",
   "UserName":"[email protected]",
   "VerifyUserName":"[email protected]",
   "Password":"A123456",
   "VerifyPassword":"A123456",
   "YKey":"123xyz",
   "YId":6,
   "Status":false,
   "KeyCode":"",
   "SsoUserName":"[email protected]",
   "SsoPassword":"",
   "BirthYear":2001
}

So everything on Posting the request from "Rest Assured" point of view looks fine, it's just that I want to update a few values from the above JSON body using JAVA so that I can create a new Student profile every time I run my function and don't have to manually change the Body.

For Every POST Student Account Creation scenario, I need to update the value for the following keys so that a new test student user account can be created:

  1. First Name
  2. Last Name and
  3. Username // "VerifyUserName" and "SSO UserName" will remain same as user name
2

There are 2 answers

5
kaweesha On BEST ANSWER

I modified the answer to get random values and pass them to json body. random value generation was taken from the accepted answer of this question.

public void testMethod() {

    List<String> randomValueList = new ArrayList<>();

    for (int i = 0; i < 3; i++) {
        String SALTCHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
        StringBuilder salt = new StringBuilder();
        Random rnd = new Random();
        while (salt.length() < 18) { // length of the random string.
            int index = (int) (rnd.nextFloat() * SALTCHARS.length());
            salt.append(SALTCHARS.charAt(index));
        }
        randomValueList.add(salt.toString());
    }

    String jsonBody = "{\n" +
            "   \"FirstName\":\"" + randomValueList.remove(0) + "\",\n" +
            "   \"MiddleInitial\":\"Q\",\n" +
            "   \"LastName\":\"" + randomValueList.remove(0) + "\",\n" +
            "   \"UserAlternateEmail\":\"\",\n" +
            "   \"SecretQuestionId\":12,\n" +
            "   \"SecretQuestionAnswer\":\"Scot\",\n" +
            "   \"UserName\":\"" + randomValueList.remove(0) + " \",\n" +
            "   \"VerifyUserName\":\"[email protected]\",\n" +
            "   \"Password\":\"A123456\",\n" +
            "   \"VerifyPassword\":\"A123456\",\n" +
            "   \"YKey\":\"123xyz\",\n" +
            "   \"YId\":6,\n" +
            "   \"Status\":false,\n" +
            "   \"KeyCode\":\"\",\n" +
            "   \"SsoUserName\":\"[email protected]\",\n" +
            "   \"SsoPassword\":\"\",\n" +
            "   \"BirthYear\":2001\n" +
            "}";

    Response response = RestAssured
            .given()
            .body(jsonBody)
            .when()
            .post("api_url")
            .then()
            .extract()
            .response();

    // Do what you need to do with the response body
}
0
Tanuj Vishnoi On

We can used pojo based approach to do certain things very easily . No matter how complex is the payload , serialization and dieselization is the best answer . I have created a framework template for api automation that can we used by putting required POJO's in path :

https://github.com/tanuj-vishnoi/pojo_api_automation

To create pojo, I also have ready to eat food for you :

https://github.com/tanuj-vishnoi/pojo_generator_using_jsonschema2pojo

for the above problem you can refer to the JsonPath lib https://github.com/json-path/JsonPath and use this code:

String mypayload = "{\n" + 
                "   \"FirstName\":\"APi1-Stud-FN\",\n" + 
                "   \"MiddleInitial\":\"Q\",\n" + 
                "   \"LastName\":\"APi1-Stud-LN\"}";
    Map map = JsonPath.parse(mypayload).read("$",Map.class);
    System.out.println(list);

once the payload converted into map you can change only required values as per the requirement

To generate random strings you can refer to lib org.apache.commons.lang3.RandomStringUtils;

public static String generateUniqueString(int lenghtOfString){
         return 
 RandomStringUtils.randomAlphabetic(lenghtOfString).toLowerCase();
 }

I recommend to store payload in a separate file and load it at runtime.