liveBook · Manning

Assertion

As explained in Unit Testing Principles, Practices, and Patterns

An assertion is a test statement that checks whether an observed result matches an expected condition.

An assertion checks whether an observed result matches the expected condition. It turns execution into verification: a test must confirm every relevant outcome, not merely traverse code paths. section 1.3

Use assertions to distinguish exercised code from tested behavior:

  • Assert explicit outcomes, such as a method's return value. section 1.3
  • Verify implicit outcomes too, such as state recorded in a property. section 1.3
  • Treat assertion-free tests as useless: they execute code but verify nothing and always pass. section 1.3
  • Use coverage as a negative indicator, not as proof that assertions establish test quality. section 1.6

Checking an observable result

A test calls IsStringLong("abc"), stores the result, and asserts that it equals false. If the method also updates WasLastStringLong, a complete test checks that second outcome rather than relying on coverage alone. section 1.3

Listing 1.3. A test with no assertions always passes.
public void Test()
{
    bool result1 = IsStringLong("abc");      #1
    bool result2 = IsStringLong("abcdef");   #2
}

Compare a test that invokes two inputs without assertions with assertion-based tests that can fail when behavior changes. section 1.3

How Unit Testing Principles, Practices, and Patterns covers it

How deep it goes
Explains explicit and implicit outcomes, then stops short of prescribing a complete assertion design method.
Examples
Uses IsStringLong, Parse, a recorded property, and an assertion-free test to contrast verification with execution.
What you can do after
Diagnose tests that execute code without verifying all relevant outcomes.
How it connects
Connects assertions with unit testing, code coverage, branch coverage, and test suite quality.

Also explained in

Compare how 15 books explain assertion →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Unit Testing Principles, Practices, and Patterns. The section links point to the parts of the book it draws on.