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 added itinera-java: with Gradle, testImplementation("org.itinera-dev:itinera-testing"), and with Maven, with <scope>test</scope>.
The program is chapter 25's shop, unchanged. Its tests are in a file of their own ending in .test.java; in your project they would go in src/test/java. 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. @DisplayNameGeneration with ReplaceUnderscores has JUnit name each test after its method, with spaces for the underscores:
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.Optional;
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.TypeToken;
import org.junit.jupiter.api.DisplayNameGeneration;
import org.junit.jupiter.api.DisplayNameGenerator;
import org.junit.jupiter.api.Test;
/** The shop's steps, each built from its inputs and run alone. */
@DisplayNameGeneration(DisplayNameGenerator.ReplaceUnderscores.class)
final class StepsTest {The steps are the shop's own, unchanged, as shown: the charge in chapter 20, its rescue step in chapter 14 and the shipping in chapter 17. 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 and chapter 12 declared them, and throwing chapter 12's errors. Each is an enum, whose constants answer as the test chooses, with a switch on the constant:
/**
* 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 TestBank implements Payments {
CHARGES,
DECLINES,
IS_DOWN;
@Override
public Optional<String> charge(String order, String card, long amount) throws NetworkDown {
return switch (this) {
case CHARGES -> Optional.of("R-" + order);
case DECLINES -> Optional.empty();
case IS_DOWN -> throw new NetworkDown();
};
}
@Override
public Optional<String> replacement(String card) {
return Optional.of(card.substring(0, card.lastIndexOf('-')) + "-2029");
}
}
/** A carrier for tests: it books and collects every parcel, or its booking system is down. */
enum TestCarrier implements Carrier {
WORKS,
IS_DOWN;
@Override
public String book(String order, long weight) throws BookingFailed {
return switch (this) {
case WORKS -> "T-" + order;
case IS_DOWN -> throw new BookingFailed();
};
}
@Override
public boolean collects(long weight) {
return true;
}
}
A test's name 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, as getContributor(), and keeps what the step contributes. Its read works as the data bag's does in chapter 11, with the type to read given as TypeToken.of(String.class):
/** Ann's charge of 40 to her card. */
private static Charge annsCharge() {
return new Charge("A-1", 40, "ann-2028", false);
}
@Test
void a_charge_the_bank_takes_gives_back_the_bank_receipt() throws NetworkDown {
var contributions = new Contributions();
var outcome = annsCharge().run(TestBank.CHARGES, contributions.getContributor());
assertEquals(Outcome.success(), outcome);
assertEquals("R-A-1", contributions.read("receipt", TypeToken.of(String.class)).orNull());
}
@Test
void a_charge_the_bank_declines_fails_with_card_expired_and_no_receipt() throws NetworkDown {
var contributions = new Contributions();
var outcome = annsCharge().run(TestBank.DECLINES, contributions.getContributor());
assertEquals(Outcome.failure("card-expired"), outcome);
assertNull(contributions.read("receipt", TypeToken.of(String.class)).orNull());
}
@Test
void a_charge_lets_the_error_of_a_bank_that_is_down_escape() {
var contributions = new Contributions();
assertThrows(
NetworkDown.class,
() -> annsCharge().run(TestBank.IS_DOWN, contributions.getContributor()));
}
The rescue step is built the same way, with the reason the test chooses:
@Test
void renewing_an_expired_card_gives_back_the_card_that_replaced_it() {
var contributions = new Contributions();
var renew = new RenewCard("jo-2024", new Reason("card-expired"));
var outcome = renew.run(TestBank.CHARGES, contributions.getContributor());
assertEquals(RescueOutcome.success(), outcome);
assertEquals("jo-2029", contributions.read("card", TypeToken.of(String.class)).orNull());
}
@Test
void a_failure_that_is_not_an_expired_card_is_not_repairable() {
var contributions = new Contributions();
var renew = new RenewCard("max-2027", new Reason("nothing-to-charge"));
var outcome = renew.run(TestBank.CHARGES, contributions.getContributor());
assertEquals(RescueOutcome.failure("not-repairable"), outcome);
}
The shipping also asks for its step reporter. StepEventReporter, from org.itineradev.itinera.step.testing, lends one, as getReporter(), and keeps what the step emits through it, in getEmitted():
/** An order's shipping, for a parcel of this weight. */
private static Ship shipping(long weight) {
return new Ship("A-1", weight, "R-A-1", false);
}
@Test
void a_parcel_of_2_kg_leaves_with_its_receipt() throws BookingFailed {
var contributions = new Contributions();
var events = new StepEventReporter();
var outcome =
shipping(2).run(TestCarrier.WORKS, contributions.getContributor(), events.getReporter());
assertEquals(Outcome.success(), outcome);
assertEquals("the parcel leaves with receipt R-A-1", events.getEmitted().get(0).message());
}
@Test
void a_parcel_of_90_kg_fails_with_over_parcel_limit_before_the_carrier_is_called()
throws BookingFailed {
var contributions = new Contributions();
var events = new StepEventReporter();
var outcome =
shipping(90).run(TestCarrier.IS_DOWN, contributions.getContributor(), events.getReporter());
assertEquals(Outcome.failure("over-parcel-limit"), outcome);
}JUnit's console launcher runs the tests, and prints a line as each starts and ends, then a count:
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 receipt :: STARTED
JUnit Jupiter > StepsTest > a charge the bank takes gives back the bank 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 119 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
- A step is an object with a method. The test builds it with its constructor, giving its inputs in order, and calls
runwith 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. - A step is tested through its outcome. The test compares the outcome
runreturns withOutcome.success()orOutcome.failure("card-expired"), the values a step'ssucceed()andfail(...)return, or withRescueOutcome's, for the rescue step. A declined card fails the charge withcard-expired, and a parcel of 90 kg fails the shipping withover-parcel-limit. That fake carrier is down, so the test passing shows that the shipping refused the parcel without calling it. - An error escapes as it would in a journey. When the bank is down, the charge's
runthrowsNetworkDown, which the executor would record as an abnormal termination, as chapter 12 showed.assertThrows(NetworkDown.class, ...)checks that the call throws it; what happens next is the workflow's decision, not the step's. - 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,
ContributionsandStepEventReporterlend 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. - 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
runasks for the service. - Test support stays in the tests.
ContributionsandStepEventReporterare initinera-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, deciding that no retry can help and refunding the charge, or the adapter of chapter 21, a method of the workflow class as chapter 23 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 method 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. |