Package org.instancio

Class Instancio

java.lang.Object
org.instancio.Instancio

public final class Instancio extends Object
Instancio API for creating instances of a class.

Usage

Create and populate an instance of a class

Returns an object fully populated with random data with non-null values.

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

Customise object's values

Returns an object populated with random data and some specified fields' values customised.

 Person person = Instancio.of(Person.class)
     .set(field(Person::getFullName), "Homer Simpson")
     .supply(all(LocalDateTime.class), () -> LocalDateTime.now())
     .generate(field(Phone::getNumber), gen -> gen.text().pattern("(#d#d#d) #d#d#d-#d#d#d#d"))
     .create();
 

Allow null values to be generated

Default behaviour is to populate every field with a non-null value. Specifying nullable will randomly generate either null or non-null value.

 Person person = Instancio.of(Person.class)
     .withNullable(field(Person::getDateOfBirth))
     .withNullable(all(Gender.class))
     .withNullable(allStrings())
     .create();
 

Ignore certain fields or classes

Ignored fields will not be populated. Their values will be null (unless they have a default value assigned).

 Person person = Instancio.of(Person.class)
     .ignore(fields().named("id"))  // Person.id, Address.id, etc.
     .ignore(all(LocalDateTime.class))
     .create();
 

Creating instances of a class from a Model

Instancio builder API parameters can be saved as a Model object using the InstancioApi.toModel() method. Objects can then be generated based on the model. Models can be useful:
  • as a prototype for creating customised instances of a class by overriding model parameters
  • reducing code duplication by re-using the same model in different parts of the code

 // Create a model
 Model<Person> simpsons = Instancio.of(Person.class)
     .supply(all(Address.class), () -> new Address("742 Evergreen Terrace", "Springfield", "US"))
     .supply(field(Person::getPets), () -> List.of(
                  new Pet(PetType.CAT, "Snowball"),
                  new Pet(PetType.DOG, "Santa's Little Helper"))
     //... other specs
     .toModel();

 // Use the above model as is
 Person person = Instancio.create(simpsons);

 // Use the model but override the name
 Person homer = Instancio.of(simpsons).set(field(Person::getName), "Homer").create();
 Person marge = Instancio.of(simpsons).set(field(Person::getName), "Marge").create();

 // A model can also used to create another model.
 // This snippet creates a new model from the original model to include a new pet.
 Model<Person> withNewPet = Instancio.of(simpsons)
     .supply(field(Person::getPets), () -> List.of(
                  new Pet(PetType.PIG, "Plopper"),
                  new Pet(PetType.CAT, "Snowball"),
                  new Pet(PetType.DOG, "Santa's Little Helper"))
     .toModel();
 

Creating generic classes

There are two options for creating instances of a generic type.

Option 1: using a TypeToken


 Pair<Apple, Banana> pairOfFruits = Instancio.create(new TypeToken<Pair<Apple, Banana>>() {}); // note the empty '{}' braces
 

Option 2: using withTypeParameters to specify the type arguments


 Pair<Apple, Banana> pairOfFruits = Instancio.of(Pair.class)
     .withTypeParameters(Apple.class, Banana.class)
     .create();
 

The second approach allows specifying arbitrary type parameters at runtime, however using this method will produce an "unchecked assignment" warning.

Since:
1.0.1
See Also:
  • Method Details

    • create

      public static <T> T create(Class<T> type)
      Creates an instance of the specified class.
      Type Parameters:
      T - the type of object
      Parameters:
      type - to create
      Returns:
      an object of the specified type
      Since:
      1.0.1
    • createList

      public static <T> List<T> createList(Class<T> elementType)
      Creates a List of random size.

      Unless configured otherwise, the generated size will be between Keys.COLLECTION_MIN_SIZE and Keys.COLLECTION_MAX_SIZE, inclusive.

      To create a list of a specific size, use ofList(Class).

      Type Parameters:
      T - element type
      Parameters:
      elementType - class to generate as list elements
      Returns:
      API builder reference
      Since:
      3.0.1
    • createSet

      public static <T> Set<T> createSet(Class<T> elementType)
      Creates a Set of random size.

      Unless configured otherwise, the generated size will be between Keys.COLLECTION_MIN_SIZE and Keys.COLLECTION_MAX_SIZE, inclusive.

      To create a Set of a specific size, use ofSet(Class).

      Type Parameters:
      T - element type
      Parameters:
      elementType - class to generate as set elements
      Returns:
      API builder reference
      Since:
      3.0.1
    • createMap

      public static <K, V> Map<K,V> createMap(Class<K> keyType, Class<V> valueType)
      Creates a Map of random size.

      Unless configured otherwise, the generated size will be between Keys.MAP_MIN_SIZE and Keys.MAP_MAX_SIZE, inclusive.

      To create a Map of a specific size, use ofMap(Class, Class).

      Type Parameters:
      K - key type
      V - value type
      Parameters:
      keyType - class to generate as map keys
      valueType - class to generate as map values
      Returns:
      API builder reference
      Since:
      3.0.1
    • stream

      public static <T> Stream<T> stream(Class<T> type)
      Creates an infinite stream of instances of the specified class.

      Example:

      
       List<Person> persons = Instancio.stream(Person.class)
           .limit(5)
           .collect(Collectors.toList());
       
      Type Parameters:
      T - the type of object
      Parameters:
      type - to create
      Returns:
      an infinite stream of objects of the specified type
      Since:
      1.1.9
    • create

      public static <T> T create(TypeTokenSupplier<T> typeToken)
      Creates an object of type specified by the type token. This method can be used for creating instances of generic types.

      Example:

      
       Pair<UUID, Person> pair = Instancio.create(new TypeToken<Pair<UUID, Person>>(){});
       
      Type Parameters:
      T - the type of object
      Parameters:
      typeToken - specifying the type to create
      Returns:
      an object of the specified type
    • stream

      public static <T> Stream<T> stream(TypeTokenSupplier<T> typeToken)
      Creates an infinite stream of objects of type specified by the type token. This method can be used for creating streams of generic types.

      Example:

      
       List<Pair<Integer, String>> pairs = Instancio.stream(new TypeToken<Pair<Integer, String>>() {})
           .limit(5)
           .collect(Collectors.toList());
       
      Type Parameters:
      T - the type of object
      Parameters:
      typeToken - specifying the type to create
      Returns:
      an infinite stream of objects of the specified type
      Since:
      1.1.9
    • create

      public static <T> T create(Model<T> model)
      Creates an object populated using the given model. If the object needs to be customised, use the of(Model) method.

      For an example of how to create a model, see InstancioApi.toModel().

      Type Parameters:
      T - the type of object
      Parameters:
      model - a model that will be used as a template for creating the object
      Returns:
      an object created based on the model
      See Also:
    • stream

      public static <T> Stream<T> stream(Model<T> model)
      Creates an infinite stream of objects populated using the given model.

      Example:

      
       Model<Person> model = Instancio.of(Person.class)
           .ignore(field(Person::getId))
           .generate(field(Person::dateOfBirth), gen -> gen.temporal().localDate().past())
           .toModel();
      
       List<Person> persons = Instancio.stream(model)
           .limit(5)
           .collect(Collectors.toList());
       
      Type Parameters:
      T - the type of object
      Parameters:
      model - that will be used to generate the objects
      Returns:
      an infinite stream of objects created based on the model
      Since:
      2.4.0
      See Also:
    • of

      public static <T> InstancioOfClassApi<T> of(Class<T> type)
      Builder version of create(Class) that allows customisation of generated values.
      
       Person person = Instancio.of(Person.class)
           .generate(allInts(), gen -> gen.ints().min(1).max(99))
           .supply(all(Address.class), () -> new Address("742 Evergreen Terrace", "Springfield", "US"))
           .supply(field("pets"), () -> List.of(
                               new Pet(PetType.CAT, "Snowball"),
                               new Pet(PetType.DOG, "Santa's Little Helper")))
           .create();
       
      Type Parameters:
      T - the type of object
      Parameters:
      type - to create
      Returns:
      API builder reference
    • of

      public static <T> InstancioApi<T> of(TypeTokenSupplier<T> typeToken)
      Builder version of create(TypeTokenSupplier) that allows customisation of generated values.
      
       List<Person> persons = Instancio.of(new TypeToken<List<Person>>(){})
           .generate(allInts(), gen -> gen.ints().min(1).max(99))
           .supply(all(Address.class), () -> new Address("742 Evergreen Terrace", "Springfield", "US"))
           .supply(field("pets"), () -> List.of(
                               new Pet(PetType.CAT, "Snowball"),
                               new Pet(PetType.DOG, "Santa's Little Helper")))
           .create();
       
      Type Parameters:
      T - the type of object
      Parameters:
      typeToken - specifying the type to create
      Returns:
      API builder reference
    • of

      public static <T> InstancioApi<T> of(Model<T> model)
      Builder version of create(Model) that allows overriding of generation parameters of an existing model.
      
       Model<Person> personModel = Instancio.of(Person.class)
           .generate(allInts(), gen -> gen.ints().min(1).max(99))
           .supply(all(Address.class), () -> new Address("742 Evergreen Terrace", "Springfield", "US"))
           .supply(field("pets"), () -> List.of(
                               new Pet(PetType.CAT, "Snowball"),
                               new Pet(PetType.DOG, "Santa's Little Helper")))
           .toModel();
      
       // Use the existing model and add/override generation parameters
       Person simpsonKid = Instancio.of(personModel)
           .generate(field("fullName"), gen -> gen.oneOf("Lisa Simpson", "Bart Simpson"))
           .create();
       
      Type Parameters:
      T - the type of object
      Parameters:
      model - specifying generation parameters of the object to create
      Returns:
      API builder reference
    • ofCartesianProduct

      @ExperimentalApi public static <T> CartesianProductApi<T> ofCartesianProduct(Class<T> type)
      Generates the Cartesian product based on the values specified via the with() method. The Cartesian product is returned as a List in lexicographical order.

      Example:

      
       record Widget(String type, int num) {}
      
       List<Widget> results = Instancio.ofCartesianProduct(Widget.class)
           .with(field(Widget::type), "FOO", "BAR", "BAZ")
           .with(field(Widget::num), 1, 2, 3)
           .list();
       

      This will produce the following list of Widget objects:

       [Widget[type=FOO, num=1],
        Widget[type=FOO, num=2],
        Widget[type=FOO, num=3],
        Widget[type=BAR, num=1],
        Widget[type=BAR, num=2],
        Widget[type=BAR, num=3],
        Widget[type=BAZ, num=1],
        Widget[type=BAZ, num=2],
        Widget[type=BAZ, num=3]]
       
      Type Parameters:
      T - the type of object
      Parameters:
      type - to create
      Returns:
      API builder reference
      Since:
      4.0.0
      See Also:
    • ofCartesianProduct

      @ExperimentalApi public static <T> CartesianProductApi<T> ofCartesianProduct(TypeTokenSupplier<T> typeToken)
      Generates the Cartesian product based on the values specified via the with() method. The Cartesian product is returned as a List in lexicographical order.

      See ofCartesianProduct(Class) for an example.

      Type Parameters:
      T - the type of object
      Parameters:
      typeToken - specifying the type to create
      Returns:
      API builder reference
      Since:
      4.0.0
      See Also:
    • ofCartesianProduct

      @ExperimentalApi public static <T> CartesianProductApi<T> ofCartesianProduct(Model<T> model)
      Generates the Cartesian product based on the values specified via the with() method. The Cartesian product is returned as a List in lexicographical order.

      See ofCartesianProduct(Class) for an example.

      Type Parameters:
      T - the type of object
      Parameters:
      model - specifying generation parameters of the object to create
      Returns:
      API builder reference
      Since:
      4.0.0
      See Also:
    • ofList

      public static <T> InstancioOfCollectionApi<List<T>> ofList(Class<T> elementType)
      Builder API for generating a List that allows customising generated values.
      Type Parameters:
      T - element type
      Parameters:
      elementType - class to generate as list elements
      Returns:
      API builder reference
      Since:
      2.0.0
    • ofList

      public static <T> InstancioOfCollectionApi<List<T>> ofList(TypeTokenSupplier<T> elementTypeToken)
      Builder API for generating a List using a type token.
      Type Parameters:
      T - element type
      Parameters:
      elementTypeToken - specifying the element type
      Returns:
      API builder reference
      Since:
      2.16.0
    • ofList

      public static <T> InstancioOfCollectionApi<List<T>> ofList(Model<T> elementModel)
      Builder API for generating a List using the specified model for list elements.
      Type Parameters:
      T - element type
      Parameters:
      elementModel - a model for creating list elements
      Returns:
      API builder reference
      Since:
      2.5.0
    • ofSet

      public static <T> InstancioOfCollectionApi<Set<T>> ofSet(Class<T> elementType)
      Builder API for generating a Set that allows customisation of generated values.
      Type Parameters:
      T - element type
      Parameters:
      elementType - class to generate as set elements
      Returns:
      API builder reference
      Since:
      2.0.0
    • ofSet

      public static <T> InstancioOfCollectionApi<Set<T>> ofSet(TypeTokenSupplier<T> elementTypeToken)
      Builder API for generating a Set using a type token.
      Type Parameters:
      T - element type
      Parameters:
      elementTypeToken - specifying the element type
      Returns:
      API builder reference
      Since:
      2.16.0
    • ofSet

      public static <T> InstancioOfCollectionApi<Set<T>> ofSet(Model<T> elementModel)
      Builder API for generating a Set using the specified model for list elements.
      Type Parameters:
      T - element type
      Parameters:
      elementModel - a model for creating set elements
      Returns:
      API builder reference
      Since:
      2.5.0
    • ofMap

      public static <K, V> InstancioOfCollectionApi<Map<K,V>> ofMap(Class<K> keyType, Class<V> valueType)
      Builder API for generating a Map that allowss customisation of generated values.
      Type Parameters:
      K - key type
      V - value type
      Parameters:
      keyType - class to generate as map keys
      valueType - class to generate as map values
      Returns:
      API builder reference
      Since:
      2.0.0
    • ofMap

      public static <K, V> InstancioOfCollectionApi<Map<K,V>> ofMap(TypeTokenSupplier<K> keyTypeToken, TypeTokenSupplier<V> valueTypeToken)
      Builder API for generating a Map using type tokens.
      Type Parameters:
      K - key type
      V - value type
      Parameters:
      keyTypeToken - specifying the key type
      valueTypeToken - specifying the value type
      Returns:
      API builder reference
      Since:
      2.16.0