in Coding, Java

Create random test objects with Java reflection

Although Java is an object oriented language, you will often separate our data and your actual business logic. You will write POJOs, entities, domain models and DTOs which you will pass to services, repositories and controllers. If you do so, you will properly need test data for those objects. Often, the data you pass will be very important as it represents the state of your application and business process. You must design it carefully to get the test results you are looking for. However, there are also some cases where the data isn’t so important – it must just be there! You need an object, filled with random data. That’s it.

Java’s reflection mechanism offers an easy method to create POJOs filled with random data. Here is a basic code snippet which will take a class, instantiate it and fills its fields with random data. Maybe it makes your test setup easier.

Best regards,
Thomas

Write a Comment

Comment

    • Correct me if I am wrong, but javafaker can do just predefined objects or you can use its RandomService, but that is overkill, I cannot use it for generation of random instances of custom objects.

      But Podam is really a hammer for fake data generation. Thanks for this whole post and references here