assertEquals

assertEquals is the assertion a test uses most: it compares two values and fails when they differ. It has an overload for each kind of value, from two integers to two objects, and the overload decides what differ means. This lesson uses the integer, the string and the object overload on one small record. The article Assertions and a failure report is the short version of this page.

The overloads

The method is overloaded, not generic: the compiler picks the version from the types of the two arguments. Two int values go to the integer version, two String values to the object version, and two objects of the same class to the object version as well. The object version calls equals on the expected value, so a class that defines equals well is compared by its content.

Point.java is a record, and a record gets equals from its components: two points with the same x and y are equal, and two with a different y are not.

public record Point(int x, int y) { }

import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; public class PointTest { @Test void integersAreEqual() { assertEquals(42, 40 + 2); } @Test void stringsAreEqualByContent() { assertEquals("JUnit", "JUnit"); } @Test void recordsAreEqualByComponents() { assertEquals(new Point(1, 2), new Point(1, 2)); } }

Expected first, actual second

The first argument is the value the test expects, the second is the value the code produced. The order does not change whether the test passes, but it changes the failure message: expected: <42> but was: <41> reads correctly only when the expected value is first. A swapped pair reports the same two numbers with the labels reversed, which sends the reader to the wrong place.

The convention also puts the literal first and the call second, which is why assertEquals(4, Calc.add(1, 3)) is the shape of the course. When both sides are computed, name them in a local variable so the test says which one it trusts.

Objects and records

The object overload compares with expected.equals(actual). A record implements equals by comparing every component, so the two points in the third test are equal even though they are different objects. A class that does not override equals falls back to the identity of the object, and then two equal-looking objects with different identities fail the test. That is the subject of the Java lesson on equals and hashCode.

The message is not lost on an object failure: the report prints the two values by calling toString. A record prints as Point[x=1, y=2], which is why the record is a good first object for this lesson.

Why not the double equals

== on two objects compares references, not contents; on two strings it asks whether they are the same object. A test written with == passes for a string literal and fails for a string built at run time, which is a false red report. assertEquals calls equals, and that is the comparison a value deserves.

The report of three tests

javac -Xlint:all -cp /opt/java-tools/junit-platform-console-standalone.jar -d out Point.java PointTest.java
junit execute --class-path out --scan-classpath --disable-ansi-colors

Thanks for using JUnit! Support its development at https://junit.org/sponsoring

╷
├─ JUnit Platform Suite ✔
├─ JUnit Jupiter ✔
│  └─ PointTest ✔
│     ├─ stringsAreEqualByContent() ✔
│     ├─ recordsAreEqualByComponents() ✔
│     └─ integersAreEqual() ✔
└─ JUnit Vintage ✔

Test run finished after 332 ms
[         4 containers found      ]
[         0 containers skipped    ]
[         4 containers started    ]
[         0 containers aborted    ]
[         4 containers successful ]
[         0 containers failed     ]
[         3 tests found           ]
[         0 tests skipped         ]
[         3 tests started         ]
[         0 tests aborted         ]
[         3 tests successful      ]
[         0 tests failed          ]

Exercises

  1. Add a test with new Point(1, 2) and new Point(2, 1). Does it pass, and what does the failure print?
  2. Replace the string literals with new String("JUnit") on one side. Does assertEquals still pass?
  3. Write the same string comparison with == and run it. Explain the difference in one sentence.
  4. Add a third component to the record and predict the new toString before you run a failing test.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. Which comparison does assertEquals use for two objects?

    Answer

    expected.equals(actual)

    The object overload calls equals, so a class with a content-based equals is compared by content.

  2. Which argument comes first in assertEquals?

    Answer

    The expected value

    The first value is what the test wants; the failure message labels it expected.

  3. Why does == make a poor assertion for strings?

    Answer

    It compares references, so two equal strings can fail

    Two strings with the same characters may be different objects, and == asks for the same object.

  4. What does this program print? public class Q1 { public static void main(String[] args) { int a = 40; int b = 2; System.out.println(a + b); } }

    Answer

    42

    The two integers are added, so println prints 42.

  5. What does this program print? public class Q2 { public static void main(String[] args) { String a = "JUnit"; String b = "JUnit"; System.out.println(a.equals(b)); } }

    Answer

    true

    equals compares the characters and both strings hold JUnit.

  6. What does this program print? public class Q3 { record Point(int x, int y) { } public static void main(String[] args) { System.out.println(new Point(1, 2).equals(new Point(1, 2))); } }

    Answer

    true

    A record compares its components, and both points have the same x and y.

  7. What does this program print? public class Q4 { public static void main(String[] args) { System.out.println("JUnit".length()); } }

    Answer

    5

    JUnit has five characters.

  8. A class does not override equals. What does assertEquals(a, b) compare for two instances?

    Answer

    The identity of the two objects

    Without an override, Object.equals compares references, so two equal-looking objects fail.

  9. What does this program print? public class Q5 { public static void main(String[] args) { int total = 0; for (int n = 1; n != 4; n++) { total += n; } System.out.println(total); } }

    Answer

    6

    The loop adds 1, 2 and 3 before n becomes 4.

  10. What does the failure message label the second value?

    Answer

    was

    The message reads expected: <...> but was: <...>.

The code on this page was built with OpenJDK 21.0.13 (javac) and run with JUnit Platform Console Launcher 1.14.3 on Alpine Linux in a Docker container.

Article author: Arthur Isaev