Testing
transmission-test tests one transformer at a time with a small DSL: fake what it depends on, send messages in
order, then await what it produced. Several routers together are tested with plain coroutine tests.
Setup
// build.gradle.kts
kotlin {
sourceSets {
commonTest.dependencies {
implementation("com.yigitozgumus:transmission-test:2.0.0-beta02")
implementation(kotlin("test"))
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:<version>")
}
}
}
import com.yigitozgumus.transmissiontest.test
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlin.test.Test
import kotlin.test.assertEquals
A First Test
class CartTransformerTest {
private val dispatcher = StandardTestDispatcher()
private val mug = Product("mug", "Mug", "🍶", Category.Gear, 1800, "")
@Test
fun `adding the same product twice increases its quantity`() = cartTransformer(dispatcher).test(dispatcher) {
fake(Catalog.productById) { mug }
send(CartEffect.AddItem("mug"))
send(CartEffect.AddItem("mug"))
val cart = awaitState(Cart.state)
assertEquals(2, cart.itemCount)
assertEquals(3600, cart.totalCents)
}
}
Create the transformer with the same StandardTestDispatcher you pass to test: processing then runs on the test
scheduler, and delays in fakes run in virtual time. test returns a TestResult, so the test function is an
expression body.
Functions
| Function | What it does |
|---|---|
fake(query) { }, fake(queryWith) { args -> } |
Answers a query in place of the transformer that serves it |
fake(state, value) |
Publishes a value as another transformer's state |
fake(command) |
Accepts a command; the result records calls (a count, or the arguments in order) |
send(message) |
Sends a signal or an effect, in order with earlier sends |
awaitState(handle) |
The handle's value once everything sent so far has been handled |
awaitData<T>(), awaitEffect<T>() |
The next data or effect of that type, skipping others |
expectNoEffects() |
Fails if an effect not yet awaited was published |
settle() |
Runs every pending message; handlers waiting in awaitSignal count as settled |
Fakes must be declared before the first send.
Faking Dependencies
Every handle the transformer calls needs a fake, as the real owner isn't in the test:
@Test
fun `address then payment places the order and empties the cart`() = checkoutTransformer(gateway, dispatcher).test(dispatcher) {
fake(Cart.summary) { cart } // answer a query another transformer would serve
val clearCart = fake(Cart.clear) // accept a command and count its calls
send(CheckoutSignal.Start)
send(CheckoutSignal.SubmitAddress(address))
send(CheckoutSignal.SubmitPayment(goodCard))
assertEquals(CheckoutStep.Confirmed("TS-1001"), awaitState(Checkout.state).step)
assertEquals(CheckoutEffect.OrderPlaced("TS-1001", 3600), awaitEffect<CheckoutEffect.OrderPlaced>())
assertEquals(1, clearCart.calls)
}
An unfaked query fails the test with ContractNotFoundException naming the handle, such as Cart.summary.
Multi-Step Flows
Send each step in order; a handler waiting in awaitSignal receives the next matching message. Check what happens
when a step is cancelled or fails as well as the happy path:
@Test
fun `cancelling at the address step ends checkout`() = checkoutTransformer(gateway, dispatcher).test(dispatcher) {
fake(Cart.summary) { cart }
send(CheckoutSignal.Start)
send(CheckoutSignal.Cancel)
assertEquals(CheckoutState(message = "Checkout cancelled."), awaitState(Checkout.state))
expectNoEffects()
}
Effects
awaitEffect<T>() returns the next effect of type T, skipping others. A targeted publish(effect, to = Cart)
is awaited the same way:
@Test
fun `promotions answer with a targeted effect`() = promotionTransformer(dispatcher).test(dispatcher) {
send(CartSignal.ApplyPromo(" save10 "))
assertEquals(PromoEffect.Applied(Promo("SAVE10", 10)), awaitEffect<PromoEffect.Applied>())
}
When an await fails, the message lists every data or effect seen during the test, in order, such as
[Other, Added(total=1)].
Several Routers Together
To test transformers in different routers, create the routers from the test's backgroundScope on one
StandardTestDispatcher, and advance it between steps. The routers are cleared when the test ends
(samples/shop/shared/src/commonTest/.../ShopFlowTest.kt):
@Test
fun `catalog and cart cooperate across routers`() = runTest(dispatcher) {
val catalog = backgroundScope.router("catalog", catalogTransformer(FakeProductRepository(), dispatcher)) {
global(); addDispatcher(dispatcher)
}
val cart = backgroundScope.router("cart", cartTransformer(dispatcher), promotionTransformer(dispatcher)) {
global(); addDispatcher(dispatcher)
}
val cartState = cart.state(Cart.state)
catalog.process(CatalogSignal.Load)
catalog.process(CatalogSignal.AddToCart("espresso"))
cart.process(CartSignal.ApplyPromo("SAVE10"))
advanceUntilIdle()
assertEquals(1, cartState.value.itemCount)
}
Guidelines
- Test behaviour: assert on published state and effects, not on how the handler got there.
- Name tests after the user's journey:
address then payment places the orderreads as a specification. - Test edge cases: empty carts, unknown codes, declined cards, cancelled steps.
- Keep domain rules in plain functions: test
CartState.changeQuantitydirectly, without a transformer. - One transformer per DSL test: fake its neighbours. Use a multi-router test only for the wiring between routers.
Classic API (Deprecated)
The TransmissionTest harness (transformer.test().testSignal(...) { lastData<T>() }) is deprecated along with the
classic API, and its checkpoint mocks will be removed in 3.0. It still works with both classic and builder
transformers.
| Classic (deprecated) | Test DSL |
|---|---|
.dataHolder(contract) { } |
fake(state, value) |
.computation(contract) { } |
fake(query) { } |
.withInitialProcessing(a, b) + .testSignal(c) { } |
send(a); send(b); send(c) |
lastData<T>(), dataStream |
awaitState(handle), awaitData<T>() |
lastEffect(), effectStream |
awaitEffect<T>(), expectNoEffects() |
The old reference is kept in Classic API: TransmissionTest.