; last updated - 2 minutes read

Writing unit tests is hard work. Much of the hardship is preparing the test data. In my daily work life, I often deal with large business objects you can't really mock. Refactoring might help, but it's not an option: I don't own the data structure.

I encountered this scenario more often than not, so I suppose it's a scenario familiar to most of you, too.

Another difficult scenario is load and performance test. Wouldn't it be nice to populate the database with thousands or millions of records to see what happens to the performance?

jPopulator comes to the rescue. jPopulator is a small framework written by Mahmoud Ben Hassine" (together with a couple of contributors).

The nice thing about jPopulator is it deals with complex data structures. The example on the jPopulator GitHub page consists of four classes, related to each other by 1:1 relations. I didn't try the framework with other test scenarios yet, but judging from the source code jPopulator also supports much more complex data structures. Be that as it may, even writing tests for those four classes is a pain if done manually: they consist of 15 attributes that have to be filled.

How to use jPopulator

Using jPopulator, generating a random Person boils down to

Populator populator = new PopulatorBuilder().build(); Person person = populator.populateBean(Person.class);

Like mentioned above, these two lines also populate the address, the gender and the street with random data. jPopulator deals with the entire object tree, treating the object Person as root.

Generating 1000 persons is just as easy:

Populator populator = new PopulatorBuilder().build(); List persons = populator.populateBeans(Person.class, 1000);

By default, jPopulator generates true random values. However, sometimes you prefer recognizable value. To do so, you define a randomizer class containing the list of desired values and register it with jPopulator:

public class FirstNameRandomizer implements Randomizer { private Random random = new Random(); /** List of desired values */ private String[] firstNames = {"Alice", "Bob", "Charlie"}; @Override public String getRandomValue() { return firstNames[random.nextInt(firstNames.length)]; } }

Conclusion

I haven't used jPopulator at work yet, but at first glance, it promises to save a lot of work. Even better, it saves a lot of stupid work. Bien joué, Mr. Ben Hassine!

Dig deeper

Project page on GitHub

jPopulator wiki

Mahmoud Ben Hassine's home page


Comments