DZone
Java Zone
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
  • Refcardz
  • Trend Reports
  • Webinars
  • Zones
  • |
    • Agile
    • AI
    • Big Data
    • Cloud
    • Database
    • DevOps
    • Integration
    • IoT
    • Java
    • Microservices
    • Open Source
    • Performance
    • Security
    • Web Dev
DZone > Java Zone > Instancio: Random Test Data Generator for Java (Part 1)

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

More testing, less plumbing

Arman Sharif user avatar by
Arman Sharif
·
May. 21, 22 · Java Zone · Tutorial
Like (9)
Save
Tweet
4.24K 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.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.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.

Popular on DZone

  • Hard Things in Computer Science
  • The Developer's Guide to SaaS Compliance
  • Kubernetes Service Types Explained In-Detail
  • When Writing Code Isn't Enough: Citizen Development and the Developer Experience

Comments

Java Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends:

DZone.com is powered by 

AnswerHub logo