Constructors & generators composition #903
-
Hello, I am curious if we can do something like this: class Author {
String name;
Address address;
List<Book> books = new ArrayList(); //
static Author of(String name, Address address) {
//my internal assignments
return new Author().setName(name).setAddress(address);
}
} class Book {
Author author;
public Book(Author author) {
author.getBooks().add(this); //bidirectional link as part of the constructor
//my OTHER constructor internal assignments
this.author = author;
}
} A book should always have an author. I have a Generator for the Author. Now, I want to have my generator to use my static factories and constructors to make objects in a valid state. I don't want to copy internal assignments as part of the Model I'd have to maintain in both places. Generator<Author> authorGenerator = (gen) -> {
return Author.of("myName", new Address());
};
Generator<Book> bookGenerator = (gen) -> {
return new Book(????); //can I reference the author other than extracting as a variable and share it between generators
}; I was thinking of reusing the generators Generator<Book> bookGenerator = (gen) -> {
Author author = authorGenerator.generate(get);
return new Book(author);
}; but then the references are different Instancio.of(Author.class)
.supply(root(), authorGenerator)
.supply(types().of(Books.class), bookGenerator)
.generate(field(Author::getBooks), gen -> gen.collection().size(1))
.withSettings(Settings.create()
.set(Keys.SET_BACK_REFERENCES, false)
.set(Keys.AFTER_GENERATE_HINT, AfterGenerate.POPULATE_NULLS)
.set(Keys.OVERWRITE_EXISTING_VALUES, true)
).create(); Do I need to create different generators?
Do I understand correctly that the idea behind the Instancio is to setup objects bypassing the domain constructors? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
@dcebotarenco - Instancio can populate objects via fields or setters. Unfortunately invoking constructors with arguments or static factories is not supported. Currently, the closest is to use Author author = Instancio.of(Author.class)
.withSettings(Settings.create().set(Keys.SET_BACK_REFERENCES, true))
.create(); I'll need to experiment a bit to see how feasible it is to implement something like this. |
Beta Was this translation helpful? Give feedback.
@dcebotarenco - Instancio can populate objects via fields or setters. Unfortunately invoking constructors with arguments or static factories is not supported.
Currently, the closest is to use
Keys.SET_BACK_REFERENCES
, but this will bypass constructors with arguments, which is not what you're looking for.I'll need to experiment a bit to see how feasible it is to implement something like this.