appmattus / kotlinfixture

Fixtures for Kotlin providing generated values for unit testing
Apache License 2.0
263 stars 15 forks source link

Referencing other factories in one `kotlinFixture` block. #102

Closed milgner closed 3 months ago

milgner commented 9 months ago

When building complex data structures, I'd like to invoke other factories from within the current one.

Something along the lines of

val myFixtures = kotlinFixture {
    factory<MyComplexObject> { buildAComplexObject() }
    factory<AnotherObject> { AnotherObject(complexStuff = buildFromPreviousFactory<MyComplexObject>()) }
}

Unfortunately I haven't found a way to do this with the current API except through multiple kotlinFixture blocks. Any ideas?

mattmook commented 3 months ago

Hi @milgner, inside the generator block of the factory you have access to fixture which will use any factories already defined. So basically for your example you can simply write:

val myFixtures = kotlinFixture {
    factory<MyComplexObject> { buildAComplexObject() }
    factory<AnotherObject> { AnotherObject(complexStuff = fixture<MyComplexObject>()) }
}