Interface Feed

All Superinterfaces:
FeedSpecAccessors, FeedSpecAnnotations

This interface provides support for using data from external sources (such as CSV or JSON files) and enables the following use cases:
  1. Generating values using methods defined by a feed.
  2. Populating values via the generate() method.
  3. Mapping feed data to an object using applyFeed().
  4. Using a feed instance as a parameterized test argument.

Examples of the first three use cases are provided below. To illustrate the usage, we will assume the existence of a persons.csv file with the following contents (formatted for clarity):

 firstName, lastName, age
 John,      Doe,      21
 Alice,     Smith,    34
 Bob,       Brown,    67
 # snip...
 

1. Generating values using methods defined by a feed

The simplest use case is mapping the file to a subclass of Feed without declaring any methods:


 @Feed.Source(resource = "persons.csv")
 interface PersonFeed extends Feed {}
 

This allows accessing the data using built-in methods provided by the Feed interface. The return type of these methods is FeedSpec. For example:


 PersonFeed feed = Instancio.ofFeed(PersonFeed.class);

 String firstName = feed.stringSpec("firstName").get(); // John
 String lastName = feed.stringSpec("lastName").get();  // Doe
 Integer age = feed.intSpec("age").get();  // 21
 

FeedSpec also allows retrieving a list of values:


 List<String> firstNamesList = feed.stringSpec("firstName").list(3); // [John, Alice, Bob]
 

Note that by default, feed data is provided in sequential order.

To make the use of feeds more convenient, subclasses of Feed can declare methods that return the FeedSpec. Method names will automatically map to the matching properties in the data source:


 @Feed.Source(resource = "persons.csv")
 interface PersonFeed extends Feed {
     FeedSpec<String> firstName();
     FeedSpec<String> lastName();
     FeedSpec<Integer> age();
 }
 

2. Populating values via the generate() method

Feeds can also be used to generate values when creating an object. For example, using the PersonFeed defined above:


 PersonFeed feed = Instancio.createFeed(PersonFeed.class);

 List<Person> personList = Instancio.ofList(Person.class)
     .size(10)
     .generate(field(Person::getFirstName), feed.firstName())
     .generate(field(Person::getLastName), feed.lastName())
     .generate(field(Person::getAge), feed.age().nullable())
     .create();
 

3. Mapping feed data to an object using applyFeed()

If feed property names match field names of the target class, data can be mapped automatically using the applyFeed() method:


 Feed personFeed = Instancio.createFeed(PersonFeed.class);

 List<Person> personList = Instancio.ofList(Person.class)
     .size(10)
     .applyFeed(all(Person.class), personFeed)
     .create();
 
Since:
5.0.0