# Testing a step alone

## What you want to do

The shop's business rules live in its steps: what a charge does when the bank declines, and which parcels the shipping refuses. You want to check each of those rules on its own, with no journey, no real bank and no real carrier.

## The code

The tests use Itinera's test support, an artifact of its own, `itinera-testing`. You add it for tests only, with no version, as [chapter 3](https://itinera-dev.org/book/kotlin/03-installing-itinera.md) added `itinera-kotlin`: with Gradle, `testImplementation("org.itinera-dev:itinera-testing")`, and with Maven, with `<scope>test</scope>`.

The program is [chapter 25](https://itinera-dev.org/book/kotlin/25-reading-the-result.md)'s shop, unchanged. Its tests are in a file of their own ending in `.test.kt`; in your project they would go in `src/test/kotlin`. They use JUnit Jupiter, the JVM's usual test framework, added for tests in the same way, and are in the shop's package, so they use its steps without importing them. Each test is a method of a class, here `StepsTest`, marked `@Test`:

Kotlin, from the program [`ch27_testing_a_step_alone.test`](https://github.com/itinera-dev/book/blob/main/kotlin/tested/ch27_testing_a_step_alone.test.kt)

```kotlin
import org.itineradev.itinera.journey.testing.Contributions
import org.itineradev.itinera.step.Outcome
import org.itineradev.itinera.step.Reason
import org.itineradev.itinera.step.RescueOutcome
import org.itineradev.itinera.step.testing.StepEventReporter
import org.itineradev.itinera.value.kotlin.typeToken
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertNull
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows

/** The shop's steps, each built from its inputs and run alone. */
class StepsTest {
```

Kotlin, the same in its asynchronous form, from the program [`ch27_testing_a_step_alone_async.test`](https://github.com/itinera-dev/book/blob/main/kotlin/tested/ch27_testing_a_step_alone_async.test.kt)

```kotlin
import kotlinx.coroutines.runBlocking
import org.itineradev.itinera.journey.testing.Contributions
import org.itineradev.itinera.step.Outcome
import org.itineradev.itinera.step.Reason
import org.itineradev.itinera.step.RescueOutcome
import org.itineradev.itinera.step.testing.AsyncStepEventReporter
import org.itineradev.itinera.value.kotlin.typeToken
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertNull
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows

/** The shop's steps, each built from its inputs and run alone. */
class StepsTest {
```

The steps are the shop's own, unchanged, as shown: the charge in [chapter 20](https://itinera-dev.org/book/kotlin/20-an-optional-input.md), its rescue step in [chapter 14](https://itinera-dev.org/book/kotlin/14-repairing-then-trying-once-more.md) and the shipping in [chapter 17](https://itinera-dev.org/book/kotlin/17-giving-up-a-step-early.md). This chapter shows only their tests.

A step meets the outside world only through its services, so the tests give it fakes of their own, implementing `Payments` and `Carrier` as [chapter 14](https://itinera-dev.org/book/kotlin/14-repairing-then-trying-once-more.md) and [chapter 12](https://itinera-dev.org/book/kotlin/12-trying-again.md) declared them, and throwing [chapter 12](https://itinera-dev.org/book/kotlin/12-trying-again.md)'s errors. Each is an enum, whose constants answer as the test chooses:

Kotlin, from the program [`ch27_testing_a_step_alone.test`](https://github.com/itinera-dev/book/blob/main/kotlin/tested/ch27_testing_a_step_alone.test.kt)

```kotlin
/**
 * A bank for tests: it answers every charge as the test chose, and has replaced every card with
 * one named after its holder that expires in 2029.
 */
enum class TestBank : Payments {
    CHARGES,
    DECLINES,
    IS_DOWN;

    override fun charge(order: String, card: String, amount: Long): String? =
        when (this) {
            CHARGES -> "R-$order"
            DECLINES -> null
            IS_DOWN -> throw NetworkDown()
        }

    override fun replacement(card: String): String? = "${card.substringBeforeLast('-')}-2029"
}

/** A carrier for tests: it books and collects every parcel, or its booking system is down. */
enum class TestCarrier : Carrier {
    WORKS,
    IS_DOWN;

    override fun book(order: String, weight: Long): String =
        when (this) {
            WORKS -> "T-$order"
            IS_DOWN -> throw BookingFailed()
        }

    override fun collects(weight: Long): Boolean = true
}

```

Kotlin, the same in its asynchronous form, from the program [`ch27_testing_a_step_alone_async.test`](https://github.com/itinera-dev/book/blob/main/kotlin/tested/ch27_testing_a_step_alone_async.test.kt)

```kotlin
/**
 * A bank for tests: it answers every charge as the test chose, and has replaced every card with
 * one named after its holder that expires in 2029.
 */
enum class TestBank : Payments {
    CHARGES,
    DECLINES,
    IS_DOWN;

    override suspend fun charge(order: String, card: String, amount: Long): String? =
        when (this) {
            CHARGES -> "R-$order"
            DECLINES -> null
            IS_DOWN -> throw NetworkDown()
        }

    override suspend fun replacement(card: String): String? =
        "${card.substringBeforeLast('-')}-2029"
}

/** A carrier for tests: it books and collects every parcel, or its booking system is down. */
enum class TestCarrier : Carrier {
    WORKS,
    IS_DOWN;

    override suspend fun book(order: String, weight: Long): String =
        when (this) {
            WORKS -> "T-$order"
            IS_DOWN -> throw BookingFailed()
        }

    override suspend fun collects(weight: Long): Boolean = true
}

```

A test's name, in backticks, says the rule it checks, and the test fails when an assertion, such as `assertEquals`, doesn't hold. The charge is tested by building it with Ann's order and calling its `run`. `Contributions`, from `org.itineradev.itinera.journey.testing`, lends the contributor `run` asks for, and keeps what the step contributes. Its `read` works as the data bag's does in [chapter 11](https://itinera-dev.org/book/kotlin/11-naming-a-journey.md), with the type to read made by `typeToken<String>()`, from `org.itineradev.itinera.value.kotlin`:

Kotlin, from the program [`ch27_testing_a_step_alone.test`](https://github.com/itinera-dev/book/blob/main/kotlin/tested/ch27_testing_a_step_alone.test.kt)

```kotlin
/** Ann's charge of 40 to her card. */
private fun annsCharge(): Charge =
    Charge(order = "A-1", amount = 40, card = "ann-2028", giftCard = false)

@Test
fun `a charge the bank takes gives back the bank's receipt`() {
    val contributions = Contributions()
    val outcome = annsCharge().run(TestBank.CHARGES, contributions.contributor)
    assertEquals(Outcome.success(), outcome)
    assertEquals("R-A-1", contributions.read("receipt", typeToken<String>()).orNull())
}

@Test
fun `a charge the bank declines fails with card-expired and no receipt`() {
    val contributions = Contributions()
    val outcome = annsCharge().run(TestBank.DECLINES, contributions.contributor)
    assertEquals(Outcome.failure("card-expired"), outcome)
    assertNull(contributions.read("receipt", typeToken<String>()).orNull())
}

@Test
fun `a charge lets the error of a bank that is down escape`() {
    val contributions = Contributions()
    assertThrows<NetworkDown> { annsCharge().run(TestBank.IS_DOWN, contributions.contributor) }
}

```

Kotlin, the same in its asynchronous form, from the program [`ch27_testing_a_step_alone_async.test`](https://github.com/itinera-dev/book/blob/main/kotlin/tested/ch27_testing_a_step_alone_async.test.kt)

```kotlin
/** Ann's charge of 40 to her card. */
private fun annsCharge(): Charge =
    Charge(order = "A-1", amount = 40, card = "ann-2028", giftCard = false)

@Test
fun `a charge the bank takes gives back the bank's receipt`() =
    runBlocking<Unit> {
        val contributions = Contributions()
        val outcome = annsCharge().run(TestBank.CHARGES, contributions.contributor)
        assertEquals(Outcome.success(), outcome)
        assertEquals("R-A-1", contributions.read("receipt", typeToken<String>()).orNull())
    }

@Test
fun `a charge the bank declines fails with card-expired and no receipt`() =
    runBlocking<Unit> {
        val contributions = Contributions()
        val outcome = annsCharge().run(TestBank.DECLINES, contributions.contributor)
        assertEquals(Outcome.failure("card-expired"), outcome)
        assertNull(contributions.read("receipt", typeToken<String>()).orNull())
    }

@Test
fun `a charge lets the error of a bank that is down escape`() =
    runBlocking<Unit> {
        val contributions = Contributions()
        assertThrows<NetworkDown> {
            annsCharge().run(TestBank.IS_DOWN, contributions.contributor)
        }
    }

```

The rescue step is built the same way, with the reason the test chooses:

Kotlin, from the program [`ch27_testing_a_step_alone.test`](https://github.com/itinera-dev/book/blob/main/kotlin/tested/ch27_testing_a_step_alone.test.kt)

```kotlin
@Test
fun `renewing an expired card gives back the card that replaced it`() {
    val contributions = Contributions()
    val renew = RenewCard(card = "jo-2024", reason = Reason("card-expired"))
    val outcome = renew.run(TestBank.CHARGES, contributions.contributor)
    assertEquals(RescueOutcome.success(), outcome)
    assertEquals("jo-2029", contributions.read("card", typeToken<String>()).orNull())
}

@Test
fun `a failure that is not an expired card is not repairable`() {
    val contributions = Contributions()
    val renew = RenewCard(card = "max-2027", reason = Reason("nothing-to-charge"))
    val outcome = renew.run(TestBank.CHARGES, contributions.contributor)
    assertEquals(RescueOutcome.failure("not-repairable"), outcome)
}

```

Kotlin, the same in its asynchronous form, from the program [`ch27_testing_a_step_alone_async.test`](https://github.com/itinera-dev/book/blob/main/kotlin/tested/ch27_testing_a_step_alone_async.test.kt)

```kotlin
@Test
fun `renewing an expired card gives back the card that replaced it`() =
    runBlocking<Unit> {
        val contributions = Contributions()
        val renew = RenewCard(card = "jo-2024", reason = Reason("card-expired"))
        val outcome = renew.run(TestBank.CHARGES, contributions.contributor)
        assertEquals(RescueOutcome.success(), outcome)
        assertEquals("jo-2029", contributions.read("card", typeToken<String>()).orNull())
    }

@Test
fun `a failure that is not an expired card is not repairable`() =
    runBlocking<Unit> {
        val contributions = Contributions()
        val renew = RenewCard(card = "max-2027", reason = Reason("nothing-to-charge"))
        val outcome = renew.run(TestBank.CHARGES, contributions.contributor)
        assertEquals(RescueOutcome.failure("not-repairable"), outcome)
    }

```

The shipping also asks for its step reporter. `StepEventReporter`, from `org.itineradev.itinera.step.testing`, lends one, and keeps what the step emits through it, in `emitted`:

Kotlin, from the program [`ch27_testing_a_step_alone.test`](https://github.com/itinera-dev/book/blob/main/kotlin/tested/ch27_testing_a_step_alone.test.kt)

```kotlin
/** An order's shipping, for a parcel of this weight. */
private fun shipping(weight: Long): Ship =
    Ship(order = "A-1", weight = weight, receipt = "R-A-1", giftCard = false)

@Test
fun `a parcel of 2 kg leaves with its receipt`() {
    val contributions = Contributions()
    val events = StepEventReporter()
    val outcome = shipping(2).run(TestCarrier.WORKS, contributions.contributor, events.reporter)
    assertEquals(Outcome.success(), outcome)
    assertEquals("the parcel leaves with receipt R-A-1", events.emitted.first().message)
}

@Test
fun `a parcel of 90 kg fails with over-parcel-limit before the carrier is called`() {
    val contributions = Contributions()
    val events = StepEventReporter()
    val outcome =
        shipping(90).run(TestCarrier.IS_DOWN, contributions.contributor, events.reporter)
    assertEquals(Outcome.failure("over-parcel-limit"), outcome)
}
```

Kotlin, the same in its asynchronous form, from the program [`ch27_testing_a_step_alone_async.test`](https://github.com/itinera-dev/book/blob/main/kotlin/tested/ch27_testing_a_step_alone_async.test.kt)

```kotlin
/** An order's shipping, for a parcel of this weight. */
private fun shipping(weight: Long): Ship =
    Ship(order = "A-1", weight = weight, receipt = "R-A-1", giftCard = false)

@Test
fun `a parcel of 2 kg leaves with its receipt`() =
    runBlocking<Unit> {
        val contributions = Contributions()
        val events = AsyncStepEventReporter()
        val outcome =
            shipping(2).run(TestCarrier.WORKS, contributions.contributor, events.reporter)
        assertEquals(Outcome.success(), outcome)
        assertEquals("the parcel leaves with receipt R-A-1", events.emitted.first().message)
    }

@Test
fun `a parcel of 90 kg fails with over-parcel-limit before the carrier is called`() =
    runBlocking<Unit> {
        val contributions = Contributions()
        val events = AsyncStepEventReporter()
        val outcome =
            shipping(90).run(TestCarrier.IS_DOWN, contributions.contributor, events.reporter)
        assertEquals(Outcome.failure("over-parcel-limit"), outcome)
    }
```

Where it differs, each example is followed by its asynchronous form, which tests [chapter 26](https://itinera-dev.org/book/kotlin/26-running-async-journeys-while-others-wait.md)'s shop the same way: its fakes' methods are `suspend` functions, each test runs its body in `runBlocking`, and the shipping's step reporter is lent by `AsyncStepEventReporter`.

JUnit's console launcher runs the tests, and prints a line as each starts and ends, then a count. It prints the same for both forms:

What running the tests of `ch27_testing_a_step_alone` prints, recorded in [`ch27_testing_a_step_alone.txt`](https://github.com/itinera-dev/book/blob/main/kotlin/tested/ch27_testing_a_step_alone.txt)

```text
JUnit Jupiter > StepsTest > a charge lets the error of a bank that is down escape() :: STARTED
JUnit Jupiter > StepsTest > a charge lets the error of a bank that is down escape() :: SUCCESSFUL
JUnit Jupiter > StepsTest > a charge the bank declines fails with card-expired and no receipt() :: STARTED
JUnit Jupiter > StepsTest > a charge the bank declines fails with card-expired and no receipt() :: SUCCESSFUL
JUnit Jupiter > StepsTest > a charge the bank takes gives back the bank's receipt() :: STARTED
JUnit Jupiter > StepsTest > a charge the bank takes gives back the bank's receipt() :: SUCCESSFUL
JUnit Jupiter > StepsTest > a failure that is not an expired card is not repairable() :: STARTED
JUnit Jupiter > StepsTest > a failure that is not an expired card is not repairable() :: SUCCESSFUL
JUnit Jupiter > StepsTest > a parcel of 2 kg leaves with its receipt() :: STARTED
JUnit Jupiter > StepsTest > a parcel of 2 kg leaves with its receipt() :: SUCCESSFUL
JUnit Jupiter > StepsTest > a parcel of 90 kg fails with over-parcel-limit before the carrier is called() :: STARTED
JUnit Jupiter > StepsTest > a parcel of 90 kg fails with over-parcel-limit before the carrier is called() :: SUCCESSFUL
JUnit Jupiter > StepsTest > renewing an expired card gives back the card that replaced it() :: STARTED
JUnit Jupiter > StepsTest > renewing an expired card gives back the card that replaced it() :: SUCCESSFUL

Test run finished after 334 ms
[         2 containers found      ]
[         0 containers skipped    ]
[         2 containers started    ]
[         0 containers aborted    ]
[         2 containers successful ]
[         0 containers failed     ]
[         7 tests found           ]
[         0 tests skipped         ]
[         7 tests started         ]
[         0 tests aborted         ]
[         7 tests successful      ]
[         0 tests failed          ]
```

What running the tests of the asynchronous form `ch27_testing_a_step_alone_async` prints, recorded in [`ch27_testing_a_step_alone_async.txt`](https://github.com/itinera-dev/book/blob/main/kotlin/tested/ch27_testing_a_step_alone_async.txt)

```text
JUnit Jupiter > StepsTest > a charge lets the error of a bank that is down escape() :: STARTED
JUnit Jupiter > StepsTest > a charge lets the error of a bank that is down escape() :: SUCCESSFUL
JUnit Jupiter > StepsTest > a charge the bank declines fails with card-expired and no receipt() :: STARTED
JUnit Jupiter > StepsTest > a charge the bank declines fails with card-expired and no receipt() :: SUCCESSFUL
JUnit Jupiter > StepsTest > a charge the bank takes gives back the bank's receipt() :: STARTED
JUnit Jupiter > StepsTest > a charge the bank takes gives back the bank's receipt() :: SUCCESSFUL
JUnit Jupiter > StepsTest > a failure that is not an expired card is not repairable() :: STARTED
JUnit Jupiter > StepsTest > a failure that is not an expired card is not repairable() :: SUCCESSFUL
JUnit Jupiter > StepsTest > a parcel of 2 kg leaves with its receipt() :: STARTED
JUnit Jupiter > StepsTest > a parcel of 2 kg leaves with its receipt() :: SUCCESSFUL
JUnit Jupiter > StepsTest > a parcel of 90 kg fails with over-parcel-limit before the carrier is called() :: STARTED
JUnit Jupiter > StepsTest > a parcel of 90 kg fails with over-parcel-limit before the carrier is called() :: SUCCESSFUL
JUnit Jupiter > StepsTest > renewing an expired card gives back the card that replaced it() :: STARTED
JUnit Jupiter > StepsTest > renewing an expired card gives back the card that replaced it() :: SUCCESSFUL

Test run finished after 389 ms
[         2 containers found      ]
[         0 containers skipped    ]
[         2 containers started    ]
[         0 containers aborted    ]
[         2 containers successful ]
[         0 containers failed     ]
[         7 tests found           ]
[         0 tests skipped         ]
[         7 tests started         ]
[         0 tests aborted         ]
[         7 tests successful      ]
[         0 tests failed          ]
```

## How it works

1. **A step is an object with a method.** The test builds it with its constructor, naming its inputs, and calls `run` with what its parameters ask for: a service, a contributor, a reporter. Their types and annotations, such as `@Service`, tell the executor what to give them in a journey; in a test, you give them yourself.
2. **A step is tested through its outcome.** The test compares the outcome `run` returns with `Outcome.success()` or `Outcome.failure("card-expired")`, the values a step's `succeed()` and `fail(...)` return, or with `RescueOutcome`'s, for the rescue step. A declined card fails the charge with `card-expired`, and a parcel of 90 kg fails the shipping with `over-parcel-limit`. That fake carrier is down, so the test passing shows that the shipping refused the parcel without calling it.
3. **An error escapes as it would in a journey.** When the bank is down, the charge's `run` throws `NetworkDown`, which the executor would record as an abnormal termination, as [chapter 12](https://itinera-dev.org/book/kotlin/12-trying-again.md) showed. `assertThrows<NetworkDown>` checks that the call throws it; what happens next is the workflow's decision, not the step's.
4. **Recorders lend what the executor would.** In a journey, the executor makes a step's contributor and step reporter for each attempt; in a test, `Contributions` and `StepEventReporter` lend them and keep what they receive. A recorder only keeps what it is given; committing a successful attempt's contributions is the executor's work.
5. **Fakes come from the test, not from the workflow.** In a journey, the workflow's providers make the bank and the carriers. Here, the test passes a fake where `run` asks for the service.
6. **Test support stays in the tests.** `Contributions` and `StepEventReporter` are in `itinera-testing`, which only the tests have. So only the test file uses them, and the book builds this program without its tests too, as it would ship.

So each rule of the shop's steps is checked without running an order. But some rules live in its policies and its workflow: `FailedShipping`, shown in [chapter 23](https://itinera-dev.org/book/kotlin/23-undoing-a-charge-when-the-shipping-fails.md), deciding that no retry can help and refunding the charge, or the adapter of [chapter 21](https://itinera-dev.org/book/kotlin/21-deciding-where-a-steps-data-comes-from.md), a method of the workflow class as [chapter 23](https://itinera-dev.org/book/kotlin/23-undoing-a-charge-when-the-shipping-fails.md) shows it, taking the weight out of the parcel. These tests never reach them.

## Outcomes

We have shown how to test each step alone, with fakes of its services and recorders lending what the executor would.

| The usual way                                                                                                  | With Itinera                                                                                 |
| -------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- |
| Testing a business rule often means setting up the whole request around it, or mocking the code that calls it. | A step is built from its inputs and run alone, with fakes passed where it asks for services. |
| What a function did is often checked through what the mocks it called received.                                | A step's test reads the outcome it returned, and what it contributed and emitted.            |
