Skip to content

Suiteopensavvy.prepared.suiteShared

Shared

class Shared<out T>

Pure, immutable lazy value which is shared between all tests.

Most of the time, we recommend using Prepared instead.

Usage

This helper allows to declare values that are needed by multiple tests. The first test to access this value computes it, after which all other tests access the same value.

suite("Random integers") {
    val randomInteger by shared { someLongOperation() }

    test("First test") {
        println(randomInteger()) // some integer
        println(randomInteger()) // the same integer
    }

    test("Second test") {
        println(randomInteger()) // still the same integer
    }
}

Notice the difference with Prepared:

  • using Prepared, all calls within the same test give the same value, but each test gets its own value.

  • using Shared, all calls give the same value, even if they are in different tests.

Values are instantiated using the shared helper.

When to use

Only use this class to hold values that are deeply immutable, are produced by pure operations, and are too costly to rerun every test.

Deep immutability is necessary because otherwise a test could modify the value and change the behavior of another test.

Produced by pure operations because the value is only computed once in the context of the first test which accesses it. Side effects, if any, will only be observable in the first test.

Additionally, shared values cannot access most features of this library, including time control, randomness control, finalizers, etc. This is because these features are based on side effects, which this class swallows silently.

To summarize:

  • if the value is mutable, use Prepared to ensure tests stay independent.

  • if the value is produced using a side effect, use Prepared to ensure all tests can observe it.

  • if the value is cheap to produce, use Prepared because tests being independent make them easier to debug.

Properties

name

val name: String

Functions

invoke

suspend operator fun invoke(): T

Computes the shared value, or returns the cached value if it has already been computed.

toString

open override fun toString(): String