https://github.com/instancio/instancio
A library that creates fully populated objects for your unit tests.
https://github.com/instancio/instancio
data-generator java junit junit-jupiter random random-generation test-automation test-data-generator testing unit-testing
Last synced: about 2 months ago
JSON representation
A library that creates fully populated objects for your unit tests.
- Host: GitHub
- URL: https://github.com/instancio/instancio
- Owner: instancio
- License: apache-2.0
- Created: 2022-03-03T06:42:29.000Z (about 3 years ago)
- Default Branch: main
- Last Pushed: 2025-02-22T05:02:08.000Z (about 2 months ago)
- Last Synced: 2025-02-23T00:38:47.887Z (about 2 months ago)
- Topics: data-generator, java, junit, junit-jupiter, random, random-generation, test-automation, test-data-generator, testing, unit-testing
- Language: Java
- Homepage: https://www.instancio.org
- Size: 10 MB
- Stars: 978
- Watchers: 12
- Forks: 59
- Open Issues: 4
-
Metadata Files:
- Readme: README.md
- Contributing: CONTRIBUTING.md
- Funding: .github/FUNDING.yml
- License: LICENSE.txt
- Security: SECURITY.md
Awesome Lists containing this project
- awesome-java - Instancio
README
[](https://search.maven.org/artifact/org.instancio/instancio-core/)
[](https://opensource.org/licenses/Apache-2.0)
[](https://sonarcloud.io/summary/new_code?id=instancio_instancio)
[](https://sonarcloud.io/summary/new_code?id=instancio_instancio)---
# 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:
```java
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:
```java
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:
```java
List persons = Instancio.ofList(Person.class).size(10).create();
```2. Create streams of objects:
```java
Stream persons = Instancio.stream(Person.class).limit(5);
```3. Create generic types:
```java
Pair, List> pairOfLists = Instancio.create(new TypeToken, List>>() {});
```4. Customise generated values:
```java
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();
```5. Create reusable templates (Models) of objects:
```java
Model 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();
```6. Use data feeds for data defined in external sources (e.g. CSV or JSON):
```java
List person = Instancio.ofList(Person.class)
.size(10)
.applyFeed(all(Person.class), feed -> feed.ofResource("persons.csv"))
.create();
```7. Define custom feeds for reuse across tests:
```java
@Feed.Source(resource = "persons.csv")
interface PersonFeed extends Feed {@TemplateSpec("${firstName} ${lastName}")
FeedSpec fullName();@FunctionSpec(params = {"fullName", "dateOfBirth"}, provider = BioProvider.class)
FeedSpec 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 = Instancio.ofList(Person.class)
.applyFeed(all(Person.class), feed -> feed.of(PersonFeed.class))
.create();
```8. Inject arguments into fields and parameters with JUnit 5 ([video tutorial](https://www.youtube.com/watch?v=H8jT43SQis0)):
```java
@ExtendWith(InstancioExtension.class)
class ExampleTest {@Given
private List randomList;@Test
void example1(@Given String randomSting, @Given(SomeCustomProvider.class) customString) {
//...
}@ValueSource(strings = {"foo", "bar"})
@ParameterizedTest
void example2(String fooOrBar, @Given long randomLong) {
// ...
}
}
```9. Run parameterized tests against many samples of generated inputs:
```java
@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](https://www.instancio.org/user-guide) (instancio.org)
- [Javadocs](https://javadoc.io/doc/org.instancio/instancio-core/latest/) (javadoc.io)
- [Quickstart](https://github.com/instancio/instancio-quickstart) (github.com) sample Maven project with usage examples```sh
git clone https://github.com/instancio/instancio-quickstart.git
```# Maven Coordinates
If you have JUnit 5 on the classpath, use the `instancio-junit` dependency.
```xml
org.instancio
instancio-junit
RELEASE
test```
To use Instancio with JUnit 4, TestNG, or standalone, use `instancio-core`:
```xml
org.instancio
instancio-core
RELEASE
test```
> [!CAUTION]
> The `org.instancio:instancio` artifact on Maven central is an older dependency that should no longer be used.# Feedback
Feedback and bug reports are greatly appreciated!
- Please submit an [issue](https://github.com/instancio/instancio/issues) for bug reports and feature requests.
- For general feedback or questions, please create a post in the [Discussions](https://github.com/instancio/instancio/discussions).Please check the [User Guide](https://www.instancio.org/user-guide), previous issues and discussions before creating a new one.
# Sponsors
If you like Instancio, please consider supporting its maintenance and development
by becoming a [sponsor](https://github.com/sponsors/instancio).A big thank you to the current project sponsors:
- [@bit-dot](https://github.com/bit-dot)
- [@darthblonderss](https://github.com/darthblonderss)
- [@mevlana14](https://github.com/mevlana14)
- [@zalabbad](https://github.com/zalabbad)Thanks to [JetBrains](https://www.jetbrains.com/opensource) and [YourKit](https://www.yourkit.com)
for supporting this project with their open source licenses.
## 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.](https://tidelift.com/subscription/pkg/maven-org.instancio.instancio-core?utm_source=maven-org.instancio.instancio-core&utm_medium=referral&utm_campaign=enterprise&utm_term=repo)