Class MapHint

java.lang.Object
org.instancio.generator.hints.MapHint
All Implemented Interfaces:
Hint<MapHint>

public final class MapHint extends Object implements Hint<MapHint>
This hint is for generators that create maps.

The responsibility of a generator is to provide an instance of a map to the engine. The map may be partially populated (with expected data). The engine takes care of populating the map with additional entries.

Sample use case

The goal is to set up a map with a couple of expected objects and let the engine populate the rest of the map with random data.

This can be achieved as follows:


 class PhonesGenerator implements Generator<Map<Long, Phone>> {

     @Override
     public Map<Long, Phone> generate(Random random) {
         Map<Long, Phone> map = new HashMap<>();
         map.put(1L, Phone.builder().number("111-222-3333").phoneType(PhoneType.CELL).build());
         map.put(2L, Phone.builder().number("111-444-5555").build()); // phoneType is null, but will be populated
         return map;
     }

     @Override
     public Hints hints() {
         return Hints.builder()
                  // tells the engine to populate null fields in the objects created in the generate() method
                 .afterGenerate(AfterGenerate.POPULATE_NULLS)
                 .with(MapHint.builder()
                          // number of additional entries to be generated and added to the map by the engine
                         .generateEntries(3)
                         .build())
                 .build();
     }
 }

 // Generator usage
 Person person = Instancio.of(Person.class)
         .supply(field("phones"), new PhonesGenerator())
         .create();

 Map<Long, Phone> map = person.getPhones();

 // Expected results:
 assertThat(map).hasSize(5);

 assertThat(map).extractingByKey(1L)
         .matches(p -> p.getNumber().equals("111-222-3333") && p.getPhoneType() == PhoneType.CELL);

 assertThat(map).extractingByKey(2L)
         .matches(p -> p.getNumber().equals("111-444-5555") && p.getPhoneType() != null);
 

Summary of results:

  • The generated map contains our custom objects as well as generated phone objects.
  • The phoneType field of "111-444-5555" has been populated since the AfterGenerate.POPULATE_NULLS was specified.
Since:
2.0.0
See Also: