liveBook · Manning

Arrange act assert pattern

As explained in 100 Java Mistakes and How to Avoid Them

The Arrange, Act, Assert pattern structures a test into setup, execution of the behavior under test, and verification of expected results.

The Arrange–Act–Assert (AAA) pattern gives a unit test three focused stages: prepare the test environment, execute the behavior under test, and verify the expected result. Keeping this structure prevents tests from drifting into unclear or ineffective forms. section 10.2

Use the stages deliberately:

  • Arrange: create and configure helper objects or other test data; omit this stage only when setup is unnecessary. section 10.2
  • Act: execute the function or behavior being tested once the environment is ready. section 10.2
  • Assert: check that the result matches expectations, using the assertion suited to the value being tested. section 10.2
  • Keep assertions after the action, especially when computation is parallel; collect asynchronous results in the original test thread before asserting. section 10.5

A passing test that tests nothing

Using assertNotNull(data.isEmpty()) instead of assertTrue(data.isEmpty()) or assertFalse(data.isEmpty()) can make a test always pass. The boolean result is autoboxed to a Boolean object, which is never null, so the assertion ignores the actual truth value. Also verify assertion argument order when optional message parameters are supported. section 10.2

Future<?> f1 = executor.submit(new AsyncRequest("/r1"));
Future<?> f2 = executor.submit(new AsyncRequest("/r2"));
f1.get();
f2.get();

Use Future results to transfer failures from parallel work back to the test thread before performing assertions. section 10.5

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Defines all three stages and explains assertion and parallel-execution pitfalls, but stops short of a complete testing-framework tutorial.
Examples
Uses malformed JUnit-style assertions, ignored Throwable handling, assertions in worker threads, CountDownLatch, and Future-based coordination.
What it assumes
Assumes familiarity with Java methods and unit-testing frameworks while defining the AAA stages and illustrating assertion behavior.
What you can do after
Apply it via JUnit or TestNG to organize tests and keep asynchronous assertion failures observable.
How it connects
Connects unit testing with assertions, autoboxing, exception handling, parallel computation, ExecutorService, and Future.

Also explained in

Compare how 6 books explain arrange act assert pattern →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Java Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.