Class ArrayHint

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

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

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

Sample use case

The goal is to set up an array with a couple of expected objects and let the engine populate the rest of the array with random data. Once populated, the expected elements the array should be shuffled to randomise the position of expected elements.

This can be achieved as follows:


  class PhonesGenerator implements Generator<Phone[]> {

     @Override
     public Phone[] generate(Random random) {
         int length = random.intRange(5, 10);
         Phone[] array = new Phone[length];
         array[0] = Phone.builder().number("111-222-3333").phoneType(PhoneType.CELL).build();
         array[1] = Phone.builder().number("111-444-5555").build(); // phoneType is null, but will be populated
         return array;
     }

     @Override
     public Hints hints() {
         return Hints.builder()
                 .with(ArrayHint.builder()
                         .shuffle(true) // shuffle the array once populated
                         .build())
                 .build();
     }
  }

  // Generator usage
  Person person = Instancio.of(Person.class)
         .supply(all(Phone[].class), new PhonesGenerator())
         .create();

  // Expected results
  assertThat(person.getPhones())
          .hasSizeBetween(5, 10)
          .doesNotContainNull()
          .anyMatch(p -> p.getNumber().equals("111-222-3333") && p.getPhoneType() == PhoneType.CELL)
          .anyMatch(p -> p.getNumber().equals("111-444-5555") && p.getPhoneType() != null); // phoneType populated
 

Summary of results:

  • The generated array contains our custom objects as well as generated phone objects.
  • The phoneType field of "111-444-5555" has been populated.
  • The array has been shuffled since the shuffle() was specified.
Since:
2.0.0
See Also: