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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Instancio: Test Data Generator for Java (Part 2)
  • Simplify Java Persistence Using Quarkus and Hibernate Reactive
  • Realistic Test Data Generation for Java Apps
  • Setting Up a CrateDB Cluster With Kubernetes to Store and Query Machine Data

Trending

  • Memory-Optimized Tables: Implementation Strategies for SQL Server
  • Designing for Sustainability: The Rise of Green Software
  • Mastering Advanced Traffic Management in Multi-Cloud Kubernetes: Scaling With Multiple Istio Ingress Gateways
  • Designing AI Multi-Agent Systems in Java
  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
7.7K 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

  • Instancio: Test Data Generator for Java (Part 2)
  • Simplify Java Persistence Using Quarkus and Hibernate Reactive
  • Realistic Test Data Generation for Java Apps
  • Setting Up a CrateDB Cluster With Kubernetes to Store and Query Machine Data

Partner Resources

×

Comments
Oops! Something Went Wrong

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

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!