DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Building Realistic Test Data in Java: A Hands-On Guide for Developers
  • Instancio: Test Data Generator for Java (Part 2)
  • Simplify Java Persistence Using Quarkus and Hibernate Reactive
  • Realistic Test Data Generation for Java Apps

Trending

  • Building Enterprise-Grade Real-Time IoT Dashboards with Vue 3, MQTT, and Kafka
  • The Agentic Agile Office: Streamlining Enterprise Agile With Autonomous AI Agents
  • Solving the Mystery: Why Java RSS Grows in Docker on M1 Macs
  • Ujorm3: A New Lightweight ORM for JavaBeans and Records
  1. DZone
  2. Coding
  3. Java
  4. Instancio: Random Test Data Generator for Java (Part 1)

Instancio: Random Test Data Generator for Java (Part 1)

More testing, less plumbing

By 
Arman Sharif user avatar
Arman Sharif
·
Updated Nov. 08, 22 · Tutorial
Likes (10)
Comment
Save
Tweet
Share
8.4K Views

Join the DZone community and get the full member experience.

Join For Free

By now hopefully all of us, developers, have embraced unit testing. Good test coverage of our codebase, combined with that green checkmark after running the tests, gives us a warm fuzzy feeling that everything is in order. While we all like that warm fuzzy feeling, writing tests usually requires some plumbing. This is the "boring part", where you create your test objects and manually set them up with dummy data. Oftentimes the values themselves don't even matter. A typical example of this is testing "converter" logic. For example, we might be converting a JPA entity to a DTO, or a JAXB class to something else. Such a test might look something like this:

Java
 
@Test
void verifyCustomer() {
  Customer customer = new Customer();
  customer.setFirstName("John");
  customer.setLastName("Doe");
  customer.setAddress(new Address("123 Main St", "Seattle", "US"));
  customer.setPhoneNumbers(List.of(
    new Phone(PhoneType.HOME, "+1", "123-44-55"),
    new Phone(PhoneType.WORK, "+1", "555-77-88")));
  // ... etc
  
  CustomerDTO customerDto = customerMapper.toDto(customer);
  
  assertThat(customerDto.getFirstName()).isEqualTo(customer.getFirstName());
  assertThat(customerDto.getLastName()).isEqualTo(customer.getLastName());
  // ... etc
}


Writing setup code like above is tedious, especially when you have a class with a lot of properties and relationships. Some projects will have "fixture" 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.

Automate the "Boring Part"

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

Java
 
@Test
void verifyCustomer() {
  Customer customer = Instancio.create(Customer.class);
  
  CustomerDTO customerDto = customerMapper.toDto(customer);
  
  assertThat(customerDto.getFirstName()).isEqualTo(customer.getFirstName());
  assertThat(customerDto.getLastName()).isEqualTo(customer.getLastName());
  // ... etc
}


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:

Java
 
Customer customer = Instancio.of(Customer.class)
  .generate(field("phoneNumbers"), gen -> gen.collection().size(3))
  .generate(field(Phone.class, "number"), gen -> gen.text().pattern("#d#d#d-#d#d-#d#d"))
  .create();


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

Java
 
gen.string().allowEmpty().minLength(10)  // string of at least 10 chars, allow empty strings
gen.text().pattern("#C#C-#d#d") //string with two uppercase and two digits, e.g. "AB-12"
gen.text().loremIpsum().words(500).paragraphs(3) // generates lorem ipsum text
gen.temporal().localDate().past() // past LocalDate
gen.arrays().length(5) // array of length 5
gen.ints().range(1, 10) // integer within given range


In addition to the generate() method, Instancio has a set() and supply() methods in case you want to set non-random values. The first method accepts the value to set, while the second a java.util.function.Supplier of the value. For example, if you want a customer with several phone numbers, all with country code "+1":

Java
 
Customer customer = Instancio.of(Customer.class)
  .generate(field("phoneNumbers"), gen -> gen.collection().minSize(3))
  .set(field(Phone.class, "countryCode"), "+1")
  .create();


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. For example, the following will create a map of 5 customers with id as the map key:

Java
 
Map<UUID, Customer> customerMap = Instancio.stream(Customer.class)
  .limit(5)
  .collect(Collectors.toMap(Customer::getId, Function.identity()));


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

Java
 
Map<UUID, Customer> customerMap = Instancio.of(Customer.class)
  .generate(all(LocalDateTime.class), gen -> gen.temporal().localDateTime().past())
  .set(field(Phone.class, "countryCode"), "+1")
  .stream()
  .limit(5)
  .collect(Collectors.toMap(Customer::getId, Function.identity()));


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; a metamodel generator that can automatically generate metamodels so that you don't have to reference fields by names; and JUnit 5 integration. More on this will be covered in Part 2 (or you can check out the documentation).

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:

XML
 
<dependency>
    <groupId>org.instancio</groupId>
    <artifactId>instancio-core</artifactId>
    <version>${instancio.version}</version>
    <scope>test</scope>
</dependency>


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

XML
 
<dependency>
    <groupId>org.instancio</groupId>
    <artifactId>instancio-junit</artifactId>
    <version>${instancio.version}</version>
    <scope>test</scope>
</dependency>


Project home on GitHub: https://github.com/instancio/instancio

Test data Java (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • Building Realistic Test Data in Java: A Hands-On Guide for Developers
  • Instancio: Test Data Generator for Java (Part 2)
  • Simplify Java Persistence Using Quarkus and Hibernate Reactive
  • Realistic Test Data Generation for Java Apps

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook