Fixtures (shared state)
A test fixture is a state holder. It initializes lazily on first use, and has a lifetime of the test suite it registers in.
Note
The fixture's value is accessed by invoking the fixture. This lets a fixture contain suspending setup code.
val StarredUsers by testSuite {
val starRepository = testFixture { // (1)!
StarRepository() // (2)!
} closeWith {
disconnect() // (3)!
}
test("alina") {
assertEquals(4, starRepository().userStars("alina")) // (4)!
}
test("peter") {
assertEquals(3, starRepository().userStars("peter")) // (5)!
}
} // (6)!
- Registers a test fixture with a lifetime of the enclosing test suite.
- The fixture's setup code can suspend.
- The fixture's (optional) tear-down code can suspend.
- The fixture initializes lazily on first use.
- The second test reuses the same fixture, sharing its setup cost and state.
- The fixture will close automatically when its suite finishes.
Info
If a fixture's value is an AutoClosable, the fixture will use its close() method, without requiring closeWith.
Using fixtures🔗
With fixtures, you can create resource-intensive state once, reuse it in multiple tests, and rely on resources to be freed when they are no longer needed.
Fixtures also support tests which build upon each other, sharing mutable state across tests.
Tip
With its default sequential execution, TestBalloon always runs tests in the order they appear in the source. This makes it easy to write tests which build upon each other.