随机更改每个“Post”请求体的JSON值,使用Java。

huangapple go评论89阅读模式
英文:

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

问题

以下是翻译好的内容:

这可能是一个重复的问题,但我在任何地方都找不到我的解决方案。因此,我要发布它。

我试图简单地发出一个关于学生账户创建场景的POST请求。我确实有一个包含所有“键:值”对的JSON文件,这些对在学生账户创建时都是必需的。

这是文件student_Profile.json的样子:

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

所以从“Rest Assured”的角度来看,关于发送请求的一切看起来都很好,只是我想使用JAVA更新上述JSON主体中的一些值,这样每次运行函数时我就可以创建一个新的学生配置文件,而不必手动更改主体。

对于每个POST学生账户创建场景,我需要更新以下键的值,以便可以创建一个新的测试学生用户账户:

  1. 名字
  2. 姓氏和
  3. 用户名 // “VerifyUserName”和“SSO UserName”将保持与用户名相同
英文:

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":"APi1-stud@xyz.com",
   "VerifyUserName":"APi1-stud@xyz.com",
   "Password":"A123456",
   "VerifyPassword":"A123456",
   "YKey":"123xyz",
   "YId":6,
   "Status":false,
   "KeyCode":"",
   "SsoUserName":"APi1-stud@xyz.com",
   "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

答案1

得分: 2

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 = "{" +
            "   \"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\":\"APi1-stud@xyz.com\",\n" +
            "   \"Password\":\"A123456\",\n" +
            "   \"VerifyPassword\":\"A123456\",\n" +
            "   \"YKey\":\"123xyz\",\n" +
            "   \"YId\":6,\n" +
            "   \"Status\":false,\n" +
            "   \"KeyCode\":\"\",\n" +
            "   \"SsoUserName\":\"APi1-stud@xyz.com\",\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
}
英文:

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&lt;String&gt; randomValueList = new ArrayList&lt;&gt;();
for (int i = 0; i &lt; 3; i++) {
String SALTCHARS = &quot;ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890&quot;;
StringBuilder salt = new StringBuilder();
Random rnd = new Random();
while (salt.length() &lt; 18) { // length of the random string.
int index = (int) (rnd.nextFloat() * SALTCHARS.length());
salt.append(SALTCHARS.charAt(index));
}
randomValueList.add(salt.toString());
}
String jsonBody = &quot;{\n&quot; +
&quot;   \&quot;FirstName\&quot;:\&quot;&quot; + randomValueList.remove(0) + &quot;\&quot;,\n&quot; +
&quot;   \&quot;MiddleInitial\&quot;:\&quot;Q\&quot;,\n&quot; +
&quot;   \&quot;LastName\&quot;:\&quot;&quot; + randomValueList.remove(0) + &quot;\&quot;,\n&quot; +
&quot;   \&quot;UserAlternateEmail\&quot;:\&quot;\&quot;,\n&quot; +
&quot;   \&quot;SecretQuestionId\&quot;:12,\n&quot; +
&quot;   \&quot;SecretQuestionAnswer\&quot;:\&quot;Scot\&quot;,\n&quot; +
&quot;   \&quot;UserName\&quot;:\&quot;&quot; + randomValueList.remove(0) + &quot; \&quot;,\n&quot; +
&quot;   \&quot;VerifyUserName\&quot;:\&quot;APi1-stud@xyz.com\&quot;,\n&quot; +
&quot;   \&quot;Password\&quot;:\&quot;A123456\&quot;,\n&quot; +
&quot;   \&quot;VerifyPassword\&quot;:\&quot;A123456\&quot;,\n&quot; +
&quot;   \&quot;YKey\&quot;:\&quot;123xyz\&quot;,\n&quot; +
&quot;   \&quot;YId\&quot;:6,\n&quot; +
&quot;   \&quot;Status\&quot;:false,\n&quot; +
&quot;   \&quot;KeyCode\&quot;:\&quot;\&quot;,\n&quot; +
&quot;   \&quot;SsoUserName\&quot;:\&quot;APi1-stud@xyz.com\&quot;,\n&quot; +
&quot;   \&quot;SsoPassword\&quot;:\&quot;\&quot;,\n&quot; +
&quot;   \&quot;BirthYear\&quot;:2001\n&quot; +
&quot;}&quot;;
Response response = RestAssured
.given()
.body(jsonBody)
.when()
.post(&quot;api_url&quot;)
.then()
.extract()
.response();
// Do what you need to do with the response body
}

答案2

得分: 1

我们可以使用基于POJO的方法来轻松地执行某些操作。无论负载有多么复杂,序列化和反序列化都是最佳答案。我已经为API自动化创建了一个框架模板,可以通过将所需的POJO放在路径中来使用:

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

为了创建POJO,我还为您准备了现成的食物:

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

对于上述问题,您可以参考JsonPath库https://github.com/json-path/JsonPath,并使用以下代码:

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

一旦负载转换为映射,您可以根据需求仅更改所需的值。

要生成随机字符串,您可以参考org.apache.commons.lang3.RandomStringUtils库;

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

我建议将负载存储在单独的文件中,并在运行时加载。

英文:

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 = &quot;{\n&quot; + 
&quot;   \&quot;FirstName\&quot;:\&quot;APi1-Stud-FN\&quot;,\n&quot; + 
&quot;   \&quot;MiddleInitial\&quot;:\&quot;Q\&quot;,\n&quot; + 
&quot;   \&quot;LastName\&quot;:\&quot;APi1-Stud-LN\&quot;}&quot;;
Map map = JsonPath.parse(mypayload).read(&quot;$&quot;,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.

huangapple
  • 本文由 发表于 2020年10月11日 03:23:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/64297379.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定