xUnit assertions

The assertion family of xUnit frameworks: equality, truth, nullity, identity, arrays, floats with a tolerance, expected exception, failure message, and the difference between a failure and an error.

  • 20 cards
  • 3 topics
  • Free

The outline, topic by topic

Each topic is weighted the way the exam weighs it.

  1. Concepts
  2. Questions
  3. Sort and link

A few cards from the deck

  • Assertion: what is it?

    Show the answer

    A test statement that compares a result with what is expected and makes the test fail when they differ.

    It is the only part of the test that can make it fail for a substantive reason: without it, the test proves nothing.

  • What does JUnit's failure message contain for this test?

    ```java
    @Test
    void somme() {
    assertEquals(5, Maths.somme(2, 2));
    }
    `

    • expected: <5> but was: <4>
    • expected: <4> but was: <5>
    • expected: <2> but was: <4>
    • expected: <true> but was: <false>
    Show the answer

    expected: <5> but was: <4>

    The first argument is the expected value (5), the second the actual value (4). Swapping the order when writing the test swaps the two numbers in the message and muddles the diagnosis.

  • To check that a method throws an exception, JUnit 5 provides the … assertion.

    Show the answer

    To check that a method throws an exception, JUnit 5 provides the assertThrows assertion.

    It takes the expected exception class and the code to run as a lambda: assertThrows(IllegalArgumentException.class, () -> f(-1)).

  • Test failure: what is it?

    Show the answer

    The verdict of a test where an assertion does not hold: the code ran, but the result is not the one expected.

    In JUnit, it is an AssertionFailedError. It points to a behaviour defect in the code under test.

  • Why does this test fail although the code is correct?

    ```java
    @Test
    void somme() {
    assertEquals(0.3, 0.1 + 0.2);
    }
    `

    • assertEquals does not know how to compare floating-point numbers
    • 0.1 + 0.2 equals 0.30000000000000004: a tolerance is missing
    • The arguments are in the wrong order: the sum must come first
    • The two numbers become distinct Double objects, whose references assertEquals compares
    Show the answer

    0.1 + 0.2 equals 0.30000000000000004: a tolerance is missing

    JUnit prints expected: <0.3> but was: <0.30000000000000004>. Binary numbers cannot represent 0.1 or 0.2 exactly. Java calls the assertEquals(double, double) version here, which compares values, not references. The version with a tolerance, assertEquals(0.3, 0.1 + 0.2, 0.0001), passes.