← Back to list

Write Unit Tests Faster with Instancio

When working on tests, we often need to create test data, which is one of the most tedious aspects of programming. Recently, I started…

Renan Schmitt in Java Tips and Tricks · 2025-01-12 19:19 · 196 claps · 2.4 min read paywalled
#java #instancio #test-data #unit-testing #junit
Open on Medium ↗
Wiki topics: 💻 · Programming

Write Unit Tests Faster with Instancio

When working on tests, we often need to create test data, which is one of the most tedious aspects of programming. Recently, I started using the Instancio library, which simplifies the process of creating objects with dummy data for unit tests.

In this article, let’s explore the power of the Instancio library (https://www.instancio.org/) and learn how to use it effectively in our tests.

Generated with bing.com/images/create.

Generated with bing.com/images/create.

Installation

If you are using Maven and JUnit 5, simply add the following to your pom.xml file:

<dependency>
    <groupId>org.instancio</groupId>
    <artifactId>instancio-junit</artifactId>
    <version>5.2.1</version>
    <scope>test</scope>
</dependency>

In all examples we are going to use the following class:

@Data
public class Person {
  private String firstName;
  private String middleName;
  private String lastName;

  private LocalDate birthDate;

  private String addressLine1;
  private String addressLine2;
  private String city;
  private String state;
  private String zipCode;
}

Mocking Objects

Let’s explore how to test a PersonService class that validates whether the fields of a Person object are filled or not, first without using Instancio and then with Instancio.

// Without Instancio

@Test
void testPersonFields(){
  // Mock Person Object
  Person person = new Person();
  person.setFirstName("RandomString1");
  person.setMiddleName("RandomString2");
  person.setLastName("RandomString3");
  person.setBirthDate(LocalDate.of(1985, 2, 3));
  person.setAddressLine1("RandomString4");
  ... // And here we add all person fields

  boolean isOk = personService.isValidPerson(person);

  Assertions.assertTrue(isOk);
}

// With Instancio

@Test
void testPersonFields(){
  // Mock Person Object
  Person person = Instancio.create(Person.class);

  boolean isOk = personService.isValidPerson(person);

  Assertions.assertTrue(isOk);
}

Instancio can automatically identify all the fields of a Person object and generate random values for them. For example: Person(firstName=PGWNCHLPX, middleName=MIFNHR, lastName=IMVAD, birthDate=2022-02-02, addressLine1=CRVR, addressLine2=NZXDTPZ, city=APWN, state=CHRJZ, zipCode=QDW)

Instancio also allows us to customize specific fields in the following ways:

  • Ignoring fields: All fields of the Person object will have random values, except those explicitly set to be ignored.
  • Setting default values for fields: Specified fields will have default values, while all other fields will retain random values.
  • Customizing random value generation rules: Specified fields will use custom rules to generate their random values.
@Test
void testPersonIgnoringMiddleName() {
  Person person = Instancio.of(Person.class)
                           .ignore(Select.field(Person::getMiddleName))
                           .create();

  boolean isOk = personService.isValidPerson(person);

  Assertions.assertTrue(isOk);
}

@Test
void testPersonSettingBirthDate() {
 Person person =
      Instancio.of(Person.class)
          .set(Select.field(Person::getBirthDate), LocalDate.of(1985, 2, 3))
          .create();

  boolean isOk = personService.isValidPerson(person);

  Assertions.assertTrue(isOk);
}

@Test
void testPersonGeneratingZipCode() {
  Person person =
      Instancio.of(Person.class)
          .generate(
              Select.field(Person::getZipCode),
              generators -> generators.string().digits().length(5))
          .create();

  boolean isOk = personService.isValidPerson(person);

  Assertions.assertTrue(isOk);
}

Creating Lists

Instancio can also generate lists with randomized elements, as shown below:

  • The first example generates a list of Person objects using the default configuration, where the number of elements varies.
  • The second example generates a list with exactly 10 elements.
  • The third example generates a list of 10 elements, setting ‘London’ as the city for all of them.
@Test
void testPersonList() {
  List<Person> personList = Instancio.createList(Person.class);

  Assertions.assertTrue(personList.size() > 0);
}

@Test
void testPersonListWithSizeEqualsTo10() {
  List<Person> personList = Instancio.ofList(Person.class).size(10).create();

  Assertions.assertEquals(10, personList.size());
}

 @Test
void testPersonListWithSizeEqualsTo10AndDefaultCity() {
  List<Person> personList =
      Instancio.ofList(Person.class)
          .size(10)
          .set(Select.field(Person::getCity), "London")
          .create();

  Assertions.assertEquals(10, personList.size());
}

Creating Maps

Creating maps is as straightforward as creating lists. Here are a few examples:

  • Using the default configuration to generate a map with an integer as the key and Person as the value.
  • Generating a similar map but with a custom generator defined for the zip code.
@Test
void testPersonMap() {
  Map<Integer, Person> personMap = 
      Instancio.createMap(Integer.class, Person.class);

  Assertions.assertFalse(personMap.isEmpty());
}

@Test
void testPersonMapWithCustomGenerator() {
  Map<Integer, Person> personMap =
      Instancio.ofMap(Integer.class, Person.class)
          .generate(
              Select.field(Person::getZipCode),
              generators -> generators.string().digits().length(5))
          .create();

  Assertions.assertEquals(5, personMap.size());
}

Creating Streams

If you need to test your code with an infinite stream, you can use Instancio:

@Test
void testPersonStream() {
  Stream<Person> personStream = Instancio.stream(Person.class);

  Assertions.assertEquals(100, personStream.limit(100).count());
}

메타데이터
post_id
b2f9e021f54d
slug
write-unit-tests-faster-with-instancio-b2f9e021f54d
url
https://medium.com/java-tips-and-tricks/write-unit-tests-faster-with-instancio-b2f9e021f54d
canonical_url
https://medium.com/java-tips-and-tricks/write-unit-tests-faster-with-instancio-b2f9e021f54d
author_url
https://medium.com/@renanschmitt
status
ok
fetched_at
2026-08-01 02:30:26