Instancio: Random Test Data Generator for Java

Arman Sharif
2 min readOct 31, 2022

--

When we write unit tests, we usually need to initialise some objects with test data. Oftentimes the values themselves don’t even matter. A typical example would be testing “converter” logic. For example, we might be converting a JPA entity to a DTO. Such a test might look something like this:

Writing setup code like above is tedious, especially when you have a class with a lot of properties and relationships. Some projects will have classes with static helper methods for creating test objects, but that’s still extra code that needs to be maintained. A better alternative is to delegate this task to a library.

Automating Data Setup

Instancio is a library that can help automate data setup by generating test data with a single method call (or a few method calls if you need to customise the data). Using Instancio, the above test will look like this:

Instancio.create(Customer.class) will generate a fully-populated Customer instance, including nested objects and collections, like addresses and the list of phone numbers. By default, Instancio will generate non-null values and non-empty collections and arrays. It's pretty easy to customize generated values. For example, the following snippet will create a Customer with 3 phone numbers with the given pattern:

The gen variable provides access to built-in generators for customising generated values. Some of the things you can do:

In addition to the generate() method, the API provides a set() and supply() methods. The first method accepts the value to set, while the second a java.util.function.Supplier of the value. For example:

This creates a customer with several phone numbers, all with country code “+1”. It also sets all LocalDateTime values to now().

Generating a Stream of Objects

In addition to creating a single object, you can also create a java.util.stream.Stream of objects. The Instancio.stream() method creates an infinite stream of distinct, fully populated instances. Since the stream is infinite, we must call limit() specifying the number of results. For example, the following will create a map of 5 customers with id as the map key:

Objects created using the stream API can be customized exactly the same way as single objects:

There’s a lot more you can do with Instancio, including creating instances of generic classes, creating models that act as a cookie cutter template for generating objects; metamodels so that you don’t have to reference fields by names; and JUnit 5 integration. Please check out the documentation for more details.

Try it out

To try it out, grab the latest version of the following dependency which is available from Maven central: https://search.maven.org/search?q=org.instancio

The standalone library:

Or if you use JUnit 5, instancio-junit provides a JUnit 5 integration, including InstancioExtension, an arguments provider for use with @ParameterizedTest, and more:

Links

--

--