A question about test factories and variable initi...
# kotest
k
A question about test factories and variable initializations (🧵)
I have a test like this:
Copy code
class MyTest : FreeSpec({
    val x = foo()
    val y = bar()
    val z = baz()

    "container a" - {
        "test1" {}
        "test2" {}
    }

    "container b" - {
        "test1" {}
        "test2" {}
    }
})
To eliminate code duplication, I used a test factory:
Copy code
class MyTest : FreeSpec({
    include(factory("a"))
    include(factory("b"))
})

private fun factory(s: String) = freeSpec {
    val x = foo()
    val y = bar()
    val z = baz()

    "container $s" - {
        "test1" {}
        "test2" {}
    }
}
Unfortunately, the code using a test factory is not functionally equivalent, because
foo()
,
bar()
and
baz()
are called twice (once per factory inclusion). I can change it so that
x
,
y
and
z
are initialized just once, in the
FreeSpec
constructor call, and passed as parameters to the factory. However, in the real application, there are too many such local variables and it would be unwieldy to pass so many parameters. Is there a recommended best practice for such a situation?