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.

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);

And the output:

{
  "name": "Cecila Starbird",
  "userName": "moistben",
  "email": "randiexyst@hotmail.co.uk",
  "profiles": [
    {
      "profileId": 964,
      "profileAdded": "Mar 19, 1973 12:00:00 AM"
    },
    {
      "profileId": 854,
      "profileAdded": "Jun 3, 1978 12:00:00 AM"
    }
  ]
}
Clone this wiki locally