Giter Site home page Giter Site logo

Instancio Maven Central License Quality Gate Status Coverage


What is it?

Instancio is a Java library that automatically creates and populates objects for your unit tests.

Instead of manually setting up test data:

Address address  = new Address();
address.setStreet("street");
address.setCity("city");
//...

Person person = new Person();
person.setFirstName("first-name");
person.setLastName("last-name");
person.setAge(22);
person.setGender(Gender.MALE);
person.setAddress(address);
//...

You can simply do the following:

Person person = Instancio.create(Person.class);

This one-liner returns a fully-populated person, including nested objects and collections.

The object is populated with random data that can be reproduced in case of test failure.

What else can Instancio do?

  1. Create collections of objects:
List<Person> persons = Instancio.ofList(Person.class).size(10).create();
  1. Create streams of objects:
Stream<Person> persons = Instancio.stream(Person.class).limit(5);
  1. Create generic types:
Pair<List<Foo>, List<Bar>> pairOfLists = Instancio.create(new TypeToken<Pair<List<Foo>, List<Bar>>>() {});
  1. Customise generated values:
Person person = Instancio.of(Person.class)
    .generate(field(Person::getDateOfBirth), gen -> gen.temporal().localDate().past())
    .generate(field(Phone::getAreaCode), gen -> gen.oneOf("604", "778"))
    .generate(field(Phone::getNumber), gen -> gen.text().pattern("#d#d#d-#d#d-#d#d"))
    .subtype(all(AbstractAddress.class), AddressImpl.class)
    .supply(all(LocalDateTime.class), () -> LocalDateTime.now())
    .onComplete(all(Person.class), (Person p) -> p.setName(p.getGender() == Gender.MALE ? "John" : "Jane"))
    .create();
  1. Create reusable templates (Models) of objects:
Model<Person> simpsons = Instancio.of(Person.class)
    .set(field(Person::getLastName), "Simpson")
    .set(field(Address::getCity), "Springfield")
    .generate(field(Person::getAge), gen -> gen.ints().range(40, 50))
    .toModel();

Person homer = Instancio.of(simpsons)
    .set(field(Person::getFirstName), "Homer")
    .create();

Person marge = Instancio.of(simpsons)
    .set(field(Person::getFirstName), "Marge")
    .create();
  1. Use data feeds for data defined in external sources (e.g. CSV or JSON):
List<Person> person = Instancio.ofList(Person.class)
    .size(10)
    .applyFeed(all(Person.class), feed -> feed.ofResource("persons.csv"))
    .create();
  1. Define custom feeds for reuse across tests:
@Feed.Source(resource = "persons.csv")
interface PersonFeed extends Feed {

  @TemplateSpec("${firstName} ${lastName}")
  FeedSpec<String> fullName();

  @FunctionSpec(params = {"fullName", "dateOfBirth"}, provider = BioProvider.class)
  FeedSpec<String> bio();

  class BioProvider implements FunctionProvider {

    String describePerson(String fullName, LocalDate dateOfBirth) {
      int age = Period.between(dateOfBirth, LocalDate.now()).getYears();
      return String.format("%s is %d years old", fullName, age);
    }
  }
}

// Usage:
List<Person> person = Instancio.ofList(Person.class)
    .applyFeed(all(Person.class), feed -> feed.of(PersonFeed.class))
    .create();
  1. Inject arguments into fields and parameters with JUnit 5:
@ExtendWith(InstancioExtension.class)
class ExampleTest {

    @Given
    private List<String> randomList;

    @Test
    void example1(@Given String randomSting, @Given(SomeCustomProvider.class) customString) {
        //...
    }

    @ValueSource(strings = {"foo", "bar"})
    @ParameterizedTest
    void example2(String fooOrBar, @Given long randomLong) {
        // ...
    }
}
  1. Run parameterized tests against many samples of generated inputs:
@ExtendWith(InstancioExtension.class)
class ExampleTest {

    @InstancioSource(samples = 1000)
    @ParameterizedTest
    void example(UUID randomUuid, Foo randomFoo, @Given(BarProvider.class) Bar customBar) {
        // runs the test method 1000 times against generated inputs
    }
}

Main Features

  • Fully reproducible data in case of test failures.
  • Support for generics, record and sealed classes, Java 21 sequenced collections.
  • Data generation based on JPA and Bean Validation annotations (Hibernate, jakarta, javax).
  • Flexible configuration options and SPIs.
  • Support for defining custom generators.
  • InstancioExtension for Junit 5 @ExtendWith.
  • Object population via fields and setters.

Getting Started

  • User guide (instancio.org)

  • Javadocs (javadoc.io)

  • Quickstart (github.com) sample Maven project with usage examples

    git clone https://github.com/instancio/instancio-quickstart.git

Maven Coordinates

If you have JUnit 5 on the classpath, use the instancio-junit dependency.

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

To use Instancio with JUnit 4, TestNG, or standalone, use instancio-core:

<dependency>
    <groupId>org.instancio</groupId>
    <artifactId>instancio-core</artifactId>
    <version>LATEST</version>
    <scope>test</scope>
</dependency>

Feedback

Feedback and bug reports are greatly appreciated!

  • Please submit an issue for bug reports and feature requests.
  • For general feedback or questions, please create a post in the Discussions.

Please check the User Guide, previous issues and discussions before creating a new one.

Third-party Extensions

Instancio-jpa is an extension on top of the Instancio library that enables the creation and population of JPA entities including the subsequent persistence of these entities using JPA for the purpose of test data generation in integration tests.

Sponsors

If you like Instancio, please consider supporting its maintenance and development by becoming a sponsor.

A big thank you to the current project sponsors:

Thanks to JetBrains and YourKit for supporting this project with their open source licenses.

JetBrains logo

YourKit logo

For Enterprise

Available as part of the Tidelift Subscription

The maintainers of Instancio and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. Learn more.

Instancio's Projects

instancio icon instancio

A library that creates fully populated objects for your unit tests.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.