← Back to list

Making Testing a Breeze: Simplifying Data Setup with Instancio Magic

Photo by Claudio Schwarz on Unsplash

Sugumar Panneerselvam · 2024-01-02 19:21 · 0 claps · 4.2 min read
#instancio #unit-testing #test-automation #dynamic-data
Open on Medium ↗
Wiki topics: 🎵 · Music & Audio

Making Testing a Breeze: Simplifying Data Setup with Instancio Magic

Photo by Claudio Schwarz on Unsplash

Photo by Claudio Schwarz on Unsplash

Introduction

Ensuring our code works correctly is crucial, and unit testing is the hero that makes it happen.

But, Have you ever encountered the below challenges when ensuring our code works flawlessly?

  • Setting up the right test data can sometimes feel like a puzzle.
  • Grapple with issues such as writing extensive code, overlooking certain test scenarios.
  • and managing complex nested data structures.

If you’ve been nodding along, you’re in the right place! Together, let’s explore the features of Instancio, a convenient Java library, in this article. It’s the solution we need to simplify these testing data challenges and make our lives easier.

Problems in Setting Up Test Data

  1. Lots of Code to Write: The traditional way of setting up test data involves writing a bunch of code, making it hard to manage and understand.
  2. Not Testing Everything: Manual/Hardcoded data setup might miss testing crucial scenarios, leading to potential issues in the real-world situations.
  3. Nested Data is Complicated: Dealing with complex nested data structures can be time-consuming and error-prone.

In the upcoming section, we will delve into these constraints with real-time use cases, exploring how Instancio, a dynamic data setup utility, can serve as a solution.

Data Made Easy: Instancio’s Magic for Effortless Test Setup

From Instancio Documentation: There are several existing libraries for generating realistic test data, such as addresses, first and last names, and so on. While Instancio also supports this use case, this is not its goal. The idea behind the project is that most unit tests do not care what the actual values are. They just require the presence of a value. Therefore, the main goal of Instancio is simply to generate fully populated objects with random data, including arrays, collections, nested collections, generic types, and so on. And it aims to do so with as little code as possible to keep the tests concise.

While Instancio boasts various features, the one that significantly streamlines about 90% of our workload is its ability to create and customize data. Let’s explore with real-time examples to witness how Instancio works its magic, optimizing our data setup process.

Use Case 1: Creating a User Object for Unit Testing

Without Instancio

Creating a user object without Instancio involves manually setting each attribute, resulting in verbose and repetitive code.

User user = new User();
user.setId(1);
user.setUsername("john_doe");
user.setEmail("john.doe@example.com");

With Instancio

Instancio simplifies object creation by allowing developers to express object instantiation and attribute setting in a concise and dynamic manner, reducing boilerplate code.

User user = Instancio.create(User.class);

Use Case 2: Creating a Collection of Addresses for User Object

Without Instancio

Building a list of objects traditionally requires the manual instantiation of each object and setting its properties, resulting in code that is hard to read and maintain.

List<Address> addresses = new ArrayList<>();

Address address1 = new Address();
address1.setStreet("123 Main St");
address1.setCity("CityA");
address1.setState("StateX");
address1.setZipCode("12345");

Address address2 = new Address();
address2.setStreet("456 Oak St");
address2.setCity("CityB");
address2.setState("StateY");
address2.setZipCode("67890");

addresses.add(address1);
addresses.add(address2);

With Instancio

Instancio facilitates the creation of object collections by providing a fluent API that generates a list of objects with specified constraints, resulting in cleaner and more adaptable test data setup.

List<Address> list = Instancio.ofList(Address.class).size(3).create();

Use Case 3: Customizing the States for Address Objects

Without Instancio

Setting values from a concrete list manually involves hardcoding specific values, limiting flexibility and making the code less adaptable to changing requirements.

List<Address> addresses = new ArrayList<>();

Address address1 = new Address();
address1.setStreet("123 Main St");
address1.setCity("CityA");

// Randomly selecting a state from the list
List<String> states = Arrays.asList("StateX", "StateY", "StateZ");
Random random = new Random();
address1.setState(states.get(random.nextInt(states.size())));

address1.setZipCode("12345");

With Instancio

Instancio allows developers to set values from a predefined list dynamically, ensuring varied and realistic data, enhancing the adaptability of tests.

Address address = Instancio.of(Address.class)
    .generate(field("city"), gen -> gen.oneOf("StateX", "StateY", "StateZ"))
    .create();

Use case 4: Setting a Static Value Across All Addresses for the User

Without Instancio

In the absence of Instancio, setting a static value across a list requires explicit iteration and manual value assignment, leading to verbose code.

List<Address> addresses = new ArrayList<>();

Address address1 = new Address();
address1.setStreet("123 Main St");
address1.setCity("CityA");
address1.setState("StateX");

Address address2 = new Address();
address2.setStreet("456 Oak St");
address2.setCity("CityB");
address2.setState("StateY");

// Setting a static value for all addresses
String zipCode = "00000";
for (Address address : addresses) {
    address.setZipCode(zipCode);
}

With Instancio

Instancio streamlines the process of setting static values across a list, reducing code complexity and improving the readability of test data setup.

User user = Instancio.of(User.class)
    .set(field(Address::getZipCode), "00000")
    .create();

Unlike a regular set method that can only be invoked on a single object, the above will set zipCode to "00000" on all generated instances of Address class

Use case 5: Reusing Common Data as Models

Without Instancio

Without Instancio, reusing common data models involves manual creation and assignment, resulting in duplicated code and increased maintenance overhead.

User john = new User();
john.setUsername("john_doe");
john.setNumberOfDaysActive(50);
john.setRole("admin");

User jane = new User();
jane.setUsername("jane_doe");
jane.setNumberOfDaysActive(50);
jane.setRole("admin");

With Instancio

Instancio simplifies the reuse of common data models by allowing developers to create reusable model instances dynamically, leading to more modular and maintainable test code.

Model<User> adminModel = Instancio.of(User.class)
    .set(field(Person::getRole), "Admin")
    .set(field(Person::getNumberOfDaysActive), 50)
    .toModel();

User john = Instancio.of(adminModel)
    .set(field(Person::getUsername), "john_doe")
    .create();

User jane = Instancio.of(adminModel)
    .set(field(Person::getUsername), "jane_doe")
    .create();

A model serves as a blueprint for constructing objects, encapsulating all the parameters specified through the builder API. Once a model is established, it enables the creation of objects without the need for redundant definition of common properties.

Conclusion

In conclusion, the showcased use cases vividly demonstrate how Instancio emerges as a powerful ally in overcoming various challenges related to unit test data preparation. From simplifying object creation to handling nested structures and customizing data, Instancio streamlines the process with elegance and efficiency.

Hope these use cases cover 90% of the constraints and solve the problems highlighted at the beginning of this article. The beauty of Instancio lies not just in its capabilities but in its ability to enhance the dynamism and adaptability of unit tests.

What’s next? Dive deeper into the world of Instancio by exploring its JUnit extension in the upcoming article. Uncover advanced techniques for leveraging the generated data effectively in unit tests.

Please share if you have come across any use cases that can be solved by Instancio. Happy testing with Instancio!

Related Articles

https://medium.com/@sugumar.p/unit-testing-shifting-focus-from-coverage-to-design-1ff0042a48a6


메타데이터
post_id
f2bca0ae965f
slug
making-testing-a-breeze-simplifying-data-setup-with-instancio-magic-f2bca0ae965f
url
https://medium.com/@sugumar.p/making-testing-a-breeze-simplifying-data-setup-with-instancio-magic-f2bca0ae965f
canonical_url
https://medium.com/@sugumar.p/making-testing-a-breeze-simplifying-data-setup-with-instancio-magic-f2bca0ae965f
author_url
https://medium.com/@sugumar.p
status
ok
fetched_at
2026-08-01 02:30:26