Skip to content

CreateJsonObject

Andrei Ciobanu edited this page Oct 3, 2017 · 4 revisions

The following example covers the generation of random JSON in a given format.

By default MockNeat doesn't support json transformation at MockUnit interface level. The solution is to work with one of the existing libraries.

In our case we will work with gson.

Example:

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Profile {
    Integer profileId;
    Date profileAdded;
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public class UserProfile {
    String name;
    String userName;
    String email;
    List<Profile> profiles;
}
MockNeat mockNeat = MockNeat.threadLocal();
Gson gson = new GsonBuilder()
                        .setPrettyPrinting()
                        .create();

String json = mockNeat
                     .reflect(UserProfile.class)
                     .field("name", mockNeat.names().full())
                     .field("userName", mockNeat.users())
                     .field("email", mockNeat.emails())
                     .field("profiles",
                                mockNeat.reflect(Profile.class)
                                        .field("profileId", mockNeat.ints().range(100, 1000))
                                        .field("profileAdded", mockNeat.localDates().toUtilDate())
                                        .list(2))
                     .map(gson::toJson) /* Transforms the UserProfile class into a 'pretty' json.
                     .val();

System.out.println(json);

Possible Output:

{
  "name": "Cecila Starbird",
  "userName": "moistben",
  "email": "[email protected]",
  "profiles": [
    {
      "profileId": 964,
      "profileAdded": "Mar 19, 1973 12:00:00 AM"
    },
    {
      "profileId": 854,
      "profileAdded": "Jun 3, 1978 12:00:00 AM"
    }
  ]
}