|
| 1 | +package org.example; |
| 2 | + |
| 3 | +import org.instancio.Instancio; |
| 4 | +import org.instancio.Model; |
| 5 | +import org.instancio.junit.InstancioExtension; |
| 6 | +import org.instancio.junit.Seed; |
| 7 | +import org.junit.jupiter.api.DisplayName; |
| 8 | +import org.junit.jupiter.api.RepeatedTest; |
| 9 | +import org.junit.jupiter.api.Test; |
| 10 | +import org.junit.jupiter.api.extension.ExtendWith; |
| 11 | + |
| 12 | +import static org.assertj.core.api.Assertions.assertThat; |
| 13 | +import static org.instancio.Select.field; |
| 14 | + |
| 15 | +@ExtendWith(InstancioExtension.class) |
| 16 | +class GithubIssueSampleTest { |
| 17 | + |
| 18 | + @Test |
| 19 | + @DisplayName("Create Foo from model") |
| 20 | + void createFooFromModel() { |
| 21 | + Model<Foo> fooModel = Factory.commonModel(Foo.class); |
| 22 | + Foo foo = Instancio.create(fooModel); |
| 23 | + |
| 24 | + assertThat(foo.getLastModified()).isAfterOrEqualTo(foo.getCreatedOn()); |
| 25 | + } |
| 26 | + |
| 27 | + @Test |
| 28 | + @DisplayName("Create Person from model") |
| 29 | + void createPersonFromModel() { |
| 30 | + Model<Person> personModel = Factory.personModel(); |
| 31 | + Person person = Instancio.create(personModel); |
| 32 | + |
| 33 | + assertThat(person.getLastModified()).isAfterOrEqualTo(person.getCreatedOn()); |
| 34 | + assertThat(person.getFullName()).startsWith(person.getFirstName() + " "); |
| 35 | + assertThat(person.getHobbies()).isNotEmpty(); |
| 36 | + } |
| 37 | + |
| 38 | + @Test |
| 39 | + @DisplayName("Create a customised Person from model") |
| 40 | + void createCustomPersonFromModel() { |
| 41 | + Model<Person> personModel = Factory.personModel(); |
| 42 | + |
| 43 | + // Customise the person before creating an instance from the model |
| 44 | + Person person = Instancio.of(personModel) |
| 45 | + .generate(field("hobbies"), gen -> gen.collection().with("music", "movies")) |
| 46 | + .create(); |
| 47 | + |
| 48 | + assertThat(person.getLastModified()).isAfterOrEqualTo(person.getCreatedOn()); |
| 49 | + assertThat(person.getFullName()).startsWith(person.getFirstName() + " "); |
| 50 | + assertThat(person.getHobbies()).contains("music", "movies"); |
| 51 | + } |
| 52 | + |
| 53 | + /** |
| 54 | + * Since we have multiple 'Instancio.create()' calls in the Factory class, |
| 55 | + * to ensure they all use same the seed, we can set it using the annotation. |
| 56 | + */ |
| 57 | + @Seed(1) |
| 58 | + @RepeatedTest(3) |
| 59 | + @DisplayName("Should generate the same person data on each test run") |
| 60 | + void createCustomPersonFromModelWithStaticData_usingAnnotation() { |
| 61 | + Person person = Instancio.of(Factory.personModel()) |
| 62 | + .generate(field("hobbies"), gen -> gen.collection().with("travel")) |
| 63 | + .create(); |
| 64 | + |
| 65 | + System.out.println(person); |
| 66 | + } |
| 67 | +} |
0 commit comments