liveBook · Manning

Delta assertion

As explained in Test Driven: Practical TDD and Acceptance TDD for Java Developers

A test assertion pattern that checks the change between an initial state and a resulting state rather than checking an absolute state.

When a test cannot rely on a fixture’s exact starting state, check how much the code changes it instead of asserting an absolute result. Record the initial state, exercise the code, then compare the result with the expected change. section 4.5.1

Listing 4.10. Example of the Delta Assertion pattern
public class TestAddingToArrayList { private ArrayList<String> list; // setup method omitted for brevity @Test public void sizeOfListReflectsItemsAddedToIt() throws Exception { int sizeBefore = list.size(); // record the "before" state list.add("something"); assertEquals(sizeBefore + 1, list.size()); // delta verification } }

The test saves the list size before adding an item, then checks that the size increased by one. section 4.5.1

This makes the assertion reflect what the test is really checking—the effect of adding an item—without depending on a particular starting size. section 4.5.1

How Test Driven: Practical TDD and Acceptance TDD for Java Developers covers it

How deep it goes
Explains recording a before state and asserting the expected change, with an ArrayList example.
Examples
Uses an ArrayList test that records its size before adding an item and expects an increase of one.
What you can do after
Apply it in Java tests by recording the initial state and asserting the expected change after exercising the code.
How it connects
Contrasts delta assertions with Resulting State Assertions and notes their combination with Guard Assertions.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Test Driven: Practical TDD and Acceptance TDD for Java Developers. The section links point to the parts of the book it draws on.