Interface InstancioOperations<T>
- Type Parameters:
T
- the type of object to create
- All Known Subinterfaces:
CartesianProductApi<T>
,InstancioApi<T>
,InstancioOfClassApi<T>
,InstancioOfCollectionApi<C>
- Since:
- 4.0.0
-
Method Summary
Modifier and TypeMethodDescriptionassign
(Assignment... assignments) Generates values based on given assignments.<V> InstancioOperations
<T> generate
(TargetSelector selector, GeneratorSpec<V> spec) Customises values using arbitrary generator specs.<V> InstancioOperations
<T> generate
(TargetSelector selector, GeneratorSpecProvider<V> gen) Customises values using built-in generators provided by thegen
parameter, of typeGenerators
.ignore
(TargetSelector selector) Specifies that a class or field should be ignored.<V> InstancioOperations
<T> onComplete
(TargetSelector selector, OnCompleteCallback<V> callback) A callback that gets invoked after an object has been fully populated.<V> InstancioOperations
<T> set
(TargetSelector selector, V value) Sets a value to matching selector targets.subtype
(TargetSelector selector, Class<?> subtype) Maps target field or class to the given subtype.<V> InstancioOperations
<T> supply
(TargetSelector selector, Supplier<V> supplier) Supplies an object using aSupplier
.<V> InstancioOperations
<T> supply
(TargetSelector selector, Generator<V> generator) Supplies an object using aGenerator
to matching selector targets.withMaxDepth
(int maxDepth) Specifies the maximum depth for populating an object.withNullable
(TargetSelector selector) Specifies that a field or class is nullable.withSeed
(long seed) Sets the seed value for the random number generator.<V> InstancioOperations
<T> withSetting
(SettingKey<V> key, V value) Override setting for the givenkey
with the specifiedvalue
.withSettings
(Settings settings) Override defaultSettings
for generating values.
-
Method Details
-
ignore
Specifies that a class or field should be ignored.Example:
Person person = Instancio.of(Person.class) .ignore(field(Phone::getPhoneNumber)) .ignore(allStrings()) .create();
will create a fully populated person, but will ignore the
getPhoneNumber
field, and all strings.Precedence
This method has higher precedence than other API methods. Once a target is ignored, no other selectors will apply. For example, the following snippet will trigger an unused selector error because
field(Phone::getNumber)
is redundant:Person person = Instancio.of(Person.class) .ignore(all(Phone.class)) .set(field(Phone::getNumber), "123-45-56") .create();
Usage with Java records
If
ignore()
targets one of the required arguments of a record constructor, then a default value for the ignored type will be generated.Example:
record PersonRecord(String name, int age) {} PersonRecord person = Instancio.of(PersonRecord.class) .ignore(allInts()) .ignore(allStrings()) .create(); // will produce: PersonRecord[name=null, age=0]
- Parameters:
selector
- for fields and/or classes this method should be applied to- Returns:
- API builder reference
- Since:
- 4.0.0
-
withNullable
Specifies that a field or class is nullable. By default, Instancio assigns non-null values to fields. If marked as nullable, Instancio will generate either a null or non-null value.Example:
Note: a type marked as nullable using this method is only nullable when declared as a field, but not as a collection element, or map key/value. For example,Person person = Instancio.of(Person.class) .withNullable(allStrings()) .withNullable(field(Person::getAddress)) .withNullable(fields().named("lastModified")) .create();
withNullable(allStrings())
will not generate nulls in aList<String>
.- Parameters:
selector
- for fields and/or classes this method should be applied to- Returns:
- API builder reference
-
set
Sets a value to matching selector targets.Example: if
Person
class contains aList<Phone>
, the following snippet will set all the country code of all phone instances to "+1".Person person = Instancio.of(Person.class) .set(field(Phone::getCountryCode), "+1") .create();
Note: Instancio will not
- populate or modify objects supplied by this method
- apply other
set()
,supply()
, orgenerate()
} methods with matching selectors to the supplied object - invoke
onComplete()
callbacks on supplied instances
- Type Parameters:
V
- type of the value- Parameters:
selector
- for fields and/or classes this method should be applied tovalue
- value to set- Returns:
- API builder reference
- Since:
- 4.0.0
- See Also:
-
supply
Supplies an object using aSupplier
.Example:
Person person = Instancio.of(Person.class) .supply(all(LocalDateTime.class), () -> LocalDateTime.now()) .supply(field(Address::getPhoneNumbers), () -> List.of( new PhoneNumber("+1", "123-45-67"), new PhoneNumber("+1", "345-67-89"))) .create();
Note: Instancio will not
- populate or modify objects supplied by this method
- apply other
set()
,supply()
, orgenerate()
} methods with matching selectors to the supplied object - invoke
onComplete()
callbacks on supplied instances
If you require the supplied object to be populated and/or selectors to be applied, use the
supply(TargetSelector, Generator)
method instead.- Type Parameters:
V
- type of the supplied value- Parameters:
selector
- for fields and/or classes this method should be applied tosupplier
- providing the value for given selector- Returns:
- API builder reference
- Since:
- 4.0.0
- See Also:
-
supply
Supplies an object using aGenerator
to matching selector targets. By default, Instancio will populate uninitialised fields of the supplied object. This includes fields withnull
or default primitive values.This method supports the following use cases.
Generate random objects
This method provides an instance of
Random
that can be used to randomise generated objects. For example, if Instancio did not support creation ofjava.time.Year
, it could be generated as follows:List<Year> years = Instancio.ofList(Year.class) .supply(all(Year.class), random -> Year.of(random.intRange(1900, 2000))) .create();
Provide a partially initialised instance
In some cases, an object may need to be created in a certain state or instantiated using a specific constructor to be in a valid state. A partially initialised instance can be supplied using this method, and Instancio will populate remaining fields that are
null
:Person person = Instancio.of(Person.class) .supply(field(Person::getAddress), random -> new Address("Springfield", "USA")) .create();
This behaviour is controlled by the
AfterGenerate
hint specified byGenerator.hints()
. Refer to theGenerator.hints()
Javadoc for details, or Custom Generators section of the user guide.- Type Parameters:
V
- type of the value to generate- Parameters:
selector
- for fields and/or classes this method should be applied togenerator
- that will provide the values- Returns:
- API builder reference
- Since:
- 4.0.0
- See Also:
-
generate
Customises values using built-in generators provided by thegen
parameter, of typeGenerators
.Example:
Person person = Instancio.of(Person.class) .generate(field(Person::getAge), gen -> gen.ints().range(18, 100)) .generate(all(LocalDate.class), gen -> gen.temporal().localDate().past()) .generate(field(Address::getPhoneNumbers), gen -> gen.collection().size(5)) .generate(field(Address::getCity), gen -> gen.oneOf("Burnaby", "Vancouver", "Richmond")) .create();
- Type Parameters:
V
- type of object to generate- Parameters:
selector
- for fields and/or classes this method should be applied togen
- provider of customisable built-in generators (also known as specs)- Returns:
- API builder reference
- See Also:
-
generate
Customises values using arbitrary generator specs.Example:
Person person = Instancio.of(Person.class) .generate(field(Person::getAge), Instancio.ints().range(18, 100)) .generate(all(LocalDate.class), Instancio.temporal().localDate().past()) .generate(field(Phone::getNumber), MyCustomGenerators.phones().northAmerican()) .create();
- Type Parameters:
V
- type of object to generate- Parameters:
selector
- for fields and/or classes this method should be applied tospec
- generator spec- Returns:
- API builder reference
- Since:
- 4.0.0
- See Also:
-
onComplete
A callback that gets invoked after an object has been fully populated.Example:
// Sets countryCode field on all instances of Phone to the specified value Person person = Instancio.of(Person.class) .onComplete(all(Phone.class), (Phone phone) -> phone.setCountryCode("+1")) .create();
Note: callbacks are never invoked on objects provided using:
Person person = Instancio.of(Person.class) .set(field(Phone::getCountryCode), "+1") .onComplete(field(Phone::getCountryCode), ...) // will not be invoked! .create();
- Type Parameters:
V
- type of object handled by the callback- Parameters:
selector
- for fields and/or classes this method should be applied tocallback
- to invoke after object has been populated- Returns:
- API builder reference
- Since:
- 4.0.0
-
subtype
Maps target field or class to the given subtype. This can be used in the following cases:- to specify an implementation for interfaces or abstract classes
- to override default implementations used by Instancio
When Instancio encounters an interface or an abstract type it is not aware of (for example, that is not part of the JDK), it will not be able to instantiate it. This method can be used to specify an implementation to use in such cases. For example:
WidgetContainer container = Instancio.of(WidgetContainer.class) .subtype(all(AbstractWidget.class), ConcreteWidget.class) .create();
Override default implementations
By default, Instancio uses certain defaults for collection classes, for example
ArrayList
forList
. If an alternative implementation is required, this method allows to specify it:Person person = Instancio.of(Person.class) .subtype(all(List.class), LinkedList.class) .create();
will use the
LinkedList
implementation for allList
s.- Parameters:
selector
- for fields and/or classes this method should be applied tosubtype
- to map the selector to- Returns:
- API builder reference
- Since:
- 4.0.0
-
assign
Generates values based on given assignments. AnAssignment
can be created using one of the builder patterns provided by theAssign
class.Assign.valueOf(originSelector).to(destinationSelector)
Assign.given(originSelector).satisfies(predicate).set(destinationSelector, value)
Assign.given(originSelector, destinationSelector).set(predicate, value)
For example, the following snippet uses
Assign.given(TargetSelector, TargetSelector)
to create an assignment that setsPhone.countryCode
based on the value of theAddress.country
field:Assignment assignment = Assign.given(field(Address::getCountry), field(Phone::getCountryCode)) .set(When.isIn("Canada", "USA"), "+1") .set(When.is("Italy"), "+39") .set(When.is("Poland"), "+48") .set(When.is("Germany"), "+49"); Person person = Instancio.of(Person.class) .generate(field(Address::getCountry), gen -> gen.oneOf("Canada", "USA", "Italy", "Poland", "Germany")) .assign(assignment) .create();
The above API allows specifying different values for a given origin/destination pair. An alternative for creating a conditional is provided by
Assign.given(TargetSelector)
. This method allows specifying different destination selectors for a given origin:Assignment shippedOrderAssignment = Assign.given(Order::getStatus) .is(OrderStatus.SHIPPED) .supply(field(Order::getDeliveryDueDate), () -> LocalDate.now().plusDays(2)); Assignment cancelledOrderAssignment = Assign.given(Order::getStatus) .is(OrderStatus.CANCELLED) .set(field(Order::getCancellationReason), "Shipping delays") .generate(field(Order::getCancellationDate), gen -> gen.temporal().instant().past()); List<Order> orders = Instancio.ofList(Order.class) .generate(all(OrderStatus.class), gen -> gen.oneOf(OrderStatus.SHIPPED, OrderStatus.CANCELLED)) .assign(shippedOrderAssignment, cancelledOrderAssignment) .create();
Limitations of assignments
Using assignments has a few limitations to be aware of.
- The origin selector must match a single target.
It must not be a
SelectorGroup
created viaSelect.all(GroupableSelector...)
or primitive/wrapper selector, such asSelect.allInts()
- An assignment where the origin selector's target is within a collection element must have a destination selector within the same collection element.
- Circular assignments will produce an error.
- Parameters:
assignments
- one or more assignment expressions for setting values- Returns:
- API builder reference
- Throws:
InstancioApiException
- if the origin selector of an assignment matches more than one target, or the assignments form a cycle- Since:
- 4.0.0
- See Also:
-
withMaxDepth
Specifies the maximum depth for populating an object. The root object is at depth zero. Children of the root object are at depth 1, grandchildren at depth 2, and so on.Instancio will populate values up to the maximum depth. Beyond that, values will be
null
unless the maximum depth is set to a higher value.The default maximum depth is defined by
Keys.MAX_DEPTH
.Note: this method is a shorthand for:
int maxDepth = 5; Person person = Instancio.of(Person.class) .withSettings(Settings.create().set(Keys.MAX_DEPTH, maxDepth)) .create();
If the maximum depth is specified using
Settings
and this method, then this method takes precedence.- Parameters:
maxDepth
- the maximum depth, must not be negative- Returns:
- API builder reference
- Since:
- 4.0.0
-
withSetting
Override setting for the givenkey
with the specifiedvalue
.- Type Parameters:
V
- the setting value type- Parameters:
key
- the setting key to overridevalue
- the setting value- Returns:
- API builder reference
- Since:
- 4.3.1
- See Also:
-
withSettings
Override defaultSettings
for generating values. TheSettings
class supports various parameters, such as collection sizes, string lengths, numeric ranges, and so on. For a list of overridable settings, refer to theKeys
class.- Parameters:
settings
- to use- Returns:
- API builder reference
- Since:
- 4.0.0
- See Also:
-
withSeed
Sets the seed value for the random number generator. If the seed is not specified, a random seed will be used. Specifying the seed is useful for reproducing test results. By specifying the seed value, the same random data will be generated again.Example:
// Generates a different UUID each time UUID result = Instancio.create(UUID.class); // Generates the same UUID each time UUID result = Instancio.of(UUID.class) .withSeed(1234) .create();
- Parameters:
seed
- for the random number generator- Returns:
- API builder reference
- Since:
- 4.0.0
-