The Itinera bookJava edition

Part 4: Running it for real, Chapter 28

Testing a hook or an adapter alone

What you want to do

Some of the shop's rules live outside its steps: failedShipping deciding that no retry can help and refunding the charge, the audit line, the customer's message, and the adapter taking the weight out of the parcel. You want to check each of them on its own, as chapter 27 checked the steps.

The code

The program is chapter 25's shop, with its tests in a file beside it, as in chapter 27. The notify policy tells customers through the role Messages, shown in chapter 19, and failedShipping gives money back through the role Refunds, shown in chapter 23, so the tests bring messages and refunds of their own, which keep what they are asked to do in a list:

Java, from the program ch28_testing_a_hook_or_an_adapter_alone.test
/** Messages for tests: it keeps each message it is asked to send, with the customer's name. */
static final class TestMessages implements Messages {
  final List<String> told = new ArrayList<>();

  @Override
  public void tell(String customer, String message) {
    told.add(customer + ": " + message);
  }
}

/** Refunds for tests: it keeps each refund it is asked to give, with its receipt. */
static final class TestRefunds implements Refunds {
  final List<String> given = new ArrayList<>();

  @Override
  public void refund(String receipt, long amount) {
    given.add(amount + " back on " + receipt);
  }
}

The policies and the adapter are the shop's own, unchanged since they were shown: the audit in chapter 20, Notify in chapter 19, FailedShipping in chapter 23, and the adapter of chapter 21, a method of the workflow class as chapter 23 shows it, and Parcel, which chapter 21 also shows. This chapter shows only their tests. FailedShipping's hook beforeRetrying is called for Ned's shipping, with the reason each test chooses, as an Optional<Reason>, and the tests read the decision it returns and the refunds it asked for, which the record Retrying holds together. Its hook givenUp is called with the cause RETRIES_EXHAUSTED, as for Oli's shipping, and the test also reads the refund it contributed:

Java, from the program ch28_testing_a_hook_or_an_adapter_alone.test
/** What {@code beforeRetrying} decided, and the refunds it asked for. */
record Retrying(OnFailure decision, List<String> refunds) {}

/**
 * What {@code beforeRetrying} decides for Ned's shipping, which failed this way after he paid 50.
 */
private static Retrying beforeRetrying(Optional<Reason> reason) {
  var refunds = new TestRefunds();
  var contributions = new Contributions();
  var decision =
      new FailedShipping()
          .beforeRetrying(reason, "R-A-12", 50, refunds, contributions.getContributor());
  return new Retrying(decision, refunds.given);
}

@Test
void failedShipping_refunds_and_gives_up_a_shipping_that_failed_with_over_parcel_limit() {
  var retrying = beforeRetrying(Optional.of(new Reason("over-parcel-limit")));
  assertEquals("no-carrier-can-take-it", retrying.decision().getFailsWorkflow().code());
  assertEquals(List.of("50 back on R-A-12"), retrying.refunds());
}

@Test
void failedShipping_lets_a_shipping_that_failed_with_too_heavy_be_retried() {
  var retrying = beforeRetrying(Optional.of(new Reason("too-heavy")));
  assertTrue(retrying.decision().getKeepsDefault());
  assertEquals(List.of(), retrying.refunds());
}

@Test
void failedShipping_lets_a_shipping_that_ended_in_an_error_be_retried() {
  var retrying = beforeRetrying(Optional.empty());
  assertTrue(retrying.decision().getKeepsDefault());
  assertEquals(List.of(), retrying.refunds());
}

@Test
void failedShipping_refunds_a_shipping_the_executor_gave_up() {
  var refunds = new TestRefunds();
  var contributions = new Contributions();
  var decision =
      new FailedShipping()
          .givenUp(
              FailureCause.RETRIES_EXHAUSTED,
              "R-A-14",
              20,
              refunds,
              contributions.getContributor());
  assertTrue(decision.getKeepsDefault());
  assertEquals(List.of("20 back on R-A-14"), refunds.given);
  assertEquals(
      "20 back on R-A-14: retries exhausted",
      contributions.read("refund", TypeToken.of(String.class)).orNull());
}

The audit's hook is called with the step's name, made by StepName.of, from org.itineradev.itinera.step, the amount, the receipt, and a contributor lent by Contributions:

Java, from the program ch28_testing_a_hook_or_an_adapter_alone.test
@Test
void audit_writes_the_step_the_amount_and_the_receipt() {
  var contributions = new Contributions();
  new Audit().charged(StepName.of("charge"), 30, "R-A-1", contributions.getContributor());
  assertEquals(
      "charge took 30, receipt R-A-1",
      contributions.read("audit", TypeToken.of(String.class)).orNull());
}

Both hooks of Notify are called with the test's messages, for Kim's gift card and Lee's failed order:

Java, from the program ch28_testing_a_hook_or_an_adapter_alone.test
@Test
void notify_gives_a_gift_card_code_and_says_sorry_for_a_failed_order() {
  var messages = new TestMessages();
  new Notify().succeeded("Kim", "A-9", Optional.empty(), Optional.of("G-A-9"), messages);
  new Notify().failed("Lee", "A-10", messages);
  assertEquals(
      List.of(
          "Kim: Order A-9 is paid: your gift card's code is G-A-9.",
          "Lee: Sorry, order A-10 could not be completed."),
      messages.told);
}

The adapter is a method of the workflow class, so the tests make the workflow, with its channel, and ask it for two of the shipping's inputs:

Java, from the program ch28_testing_a_hook_or_an_adapter_alone.test
/** Gil's parcel, as the warehouse describes it. */
private static Parcel gilsParcel() {
  return new Parcel(60, List.of(120L, 80L, 60L));
}

@Test
void parcels_gives_the_shipping_the_parcel_weight() {
  var weight = new Orders("email").parcels("weight", gilsParcel());
  assertEquals(new Supplied.Value(60L), weight);
}

@Test
void parcels_leaves_every_other_input_to_the_data_bag() {
  var receipt = new Orders("email").parcels("receipt", gilsParcel());
  assertEquals(Supplied.FromDataBag.INSTANCE, receipt);
}

JUnit's console launcher prints:

What running the tests of ch28_testing_a_hook_or_an_adapter_alone prints, recorded in ch28_testing_a_hook_or_an_adapter_alone.txt
JUnit Jupiter > HooksTest > audit writes the step the amount and the receipt :: STARTED
JUnit Jupiter > HooksTest > audit writes the step the amount and the receipt :: SUCCESSFUL
JUnit Jupiter > HooksTest > failedShipping lets a shipping that ended in an error be retried :: STARTED
JUnit Jupiter > HooksTest > failedShipping lets a shipping that ended in an error be retried :: SUCCESSFUL
JUnit Jupiter > HooksTest > failedShipping lets a shipping that failed with too heavy be retried :: STARTED
JUnit Jupiter > HooksTest > failedShipping lets a shipping that failed with too heavy be retried :: SUCCESSFUL
JUnit Jupiter > HooksTest > failedShipping refunds a shipping the executor gave up :: STARTED
JUnit Jupiter > HooksTest > failedShipping refunds a shipping the executor gave up :: SUCCESSFUL
JUnit Jupiter > HooksTest > failedShipping refunds and gives up a shipping that failed with over parcel limit :: STARTED
JUnit Jupiter > HooksTest > failedShipping refunds and gives up a shipping that failed with over parcel limit :: SUCCESSFUL
JUnit Jupiter > HooksTest > notify gives a gift card code and says sorry for a failed order :: STARTED
JUnit Jupiter > HooksTest > notify gives a gift card code and says sorry for a failed order :: SUCCESSFUL
JUnit Jupiter > HooksTest > parcels gives the shipping the parcel weight :: STARTED
JUnit Jupiter > HooksTest > parcels gives the shipping the parcel weight :: SUCCESSFUL
JUnit Jupiter > HooksTest > parcels leaves every other input to the data bag :: STARTED
JUnit Jupiter > HooksTest > parcels leaves every other input to the data bag :: SUCCESSFUL

Test run finished after 116 ms
[         2 containers found      ]
[         0 containers skipped    ]
[         2 containers started    ]
[         0 containers aborted    ]
[         2 containers successful ]
[         0 containers failed     ]
[         8 tests found           ]
[         0 tests skipped         ]
[         8 tests started         ]
[         0 tests aborted         ]
[         8 tests successful      ]
[         0 tests failed          ]

How it works

  1. A hook is a method. The test makes the policy with its constructor, which takes nothing, and calls the hook with what its parameters ask for. Their types and annotations, such as Optional<Reason>, @FromWorkflow or @Role, only tell the executor what to give them in a journey. Nothing else changes: the policies are the shop's own.
  2. A hook is tested through its decision. beforeRetrying returns an OnFailure, and givenUp one too. OnFailure's own methods read it: getKeepsDefault() says the hook kept the default, so the executor does what it would have done without the policy, and getFailsWorkflow() gives the reason the hook fails the journey with, or null when it doesn't. The tests give the hook every case it has to handle, including no reason at all, an empty Optional, which is what it gets after an attempt that ended in an error.
  3. A role is faked like a service. Notify asks for Messages, and FailedShipping for Refunds, so the tests pass their own TestMessages and TestRefunds, and read what the hooks told whom and what they gave back. refund, the policy's own private method, is tested through the two hooks that call it.
  4. A hook's contributions are read as a step's. The audit and givenUp contribute through the contributor Contributions lends, and the tests read it back with read, as in chapter 27.
  5. An adapter is tested through what it supplies. parcels returns what supply(...) makes for the weight, a Supplied.Value holding it, and what fromDataBag() makes for every other input, Supplied.FromDataBag.INSTANCE, which leaves the input to the data bag. Both are values the test compares, from org.itineradev.itinera.workflow. The test gives the adapter the parcel itself, as a journey would give it from the data bag.

So each rule of the shop's policies and its workflow is checked alone too. But nothing yet checks how the workflow puts them together: that a declined card is rescued, that Ned's shipping is given up after its first attempt, and that every customer is told. A journey checks that, and a journey runs the steps, with their bank and their carriers.

Outcomes

We have shown how to test a policy's hooks and a workflow's input adapter alone, by calling them as methods.

The usual way With Itinera
Logic that runs around a call, such as a retry rule or an audit line, is often tested only by running the whole call. A hook is a method, called by the test with the data it asks for, and its decision is a value the test reads.
Code that converts data for a function often sits inside it, tested only with it. An input adapter is a method of the workflow, tested on its own with the data it reads.