Core JUnit assertions
40 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)A ShopLite test can say "the total is wrong" without showing which number it expected. Worse, a careless assertion can pass when it should fail, or fail with a message that lies.
assertEquals, assertNotEquals, assertTrue, assertFalse, assertNull
Assertion is a check that throws an error when it is false, which makes the test fail with a message. JUnit 5 assertions are static methods of org.junit.jupiter.api.Assertions.
These tests check a Cart with the five everyday assertions. Each one checks one kind of fact.
Example 1 · The basic assertions on a cart
Runs in: a Maven project with JUnit 5 (shoplite-api: src/test/java/com/shoplite/cart)
package com.shoplite.cart;
import static org.junit.jupiter.api.Assertions.assertEquals;import static org.junit.jupiter.api.Assertions.assertFalse;import static org.junit.jupiter.api.Assertions.assertNotEquals;import static org.junit.jupiter.api.Assertions.assertNotNull;import static org.junit.jupiter.api.Assertions.assertNull;import static org.junit.jupiter.api.Assertions.assertTrue;
import java.math.BigDecimal;import java.util.Map;
import org.junit.jupiter.api.Test;
class CartAssertionsTest {
@Test void addingAPenCountsOneItem() { Cart cart = new Cart();
cart.add("PEN-BLU", new BigDecimal("10.00"), 1);
assertEquals(1, cart.itemCount()); }
@Test void aCartWithItemsIsNotEmpty() { Cart cart = new Cart();
cart.add("PEN-BLU", new BigDecimal("10.00"), 1);
assertFalse(cart.lines().isEmpty()); assertTrue(cart.itemCount() > 0); }
@Test void addingMoreChangesTheTotal() { Cart cart = new Cart(); cart.add("PEN-BLU", new BigDecimal("10.00"), 1); BigDecimal before = cart.total();
cart.add("PEN-BLU", new BigDecimal("10.00"), 1);
assertNotEquals(before, cart.total()); }
@Test void anUnknownCouponHasNoDiscount() { Map<String, Integer> coupons = Map.of("FEST20", 20);
assertNotNull(coupons.get("FEST20")); assertNull(coupons.get("NOCODE")); }}[INFO] Running com.shoplite.cart.CartAssertionsTest [INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.046 s -- in com.shoplite.cart.CartAssertionsTest
What this code does
- Each assertion is imported statically, so the tests read like sentences: assert equals 1, assert false that the lines are empty.
assertNotEqualschecks that something changed without fixing the new value; when you know the new value,assertEquals(new BigDecimal("20.00"), cart.total())says more. The two pairs inaCartWithItemsIsNotEmptyandanUnknownCouponHasNoDiscounteach describe a single behaviour.
assertEquals compares primitives with == and objects with equals(). Prefer the assertion that says the most: assertEquals(3, cart.itemCount()) fails with expected: <3> but was: <2>, while assertTrue(cart.itemCount() == 3) only says expected: <true> but was: <false>, hiding the real number. What each failure prints:
assertEquals(3, 2)→expected: <3> but was: <2>assertNotEquals(5, 5)→expected: not equal but was: <5>assertTrue(false)→expected: <true> but was: <false>assertNull("x")→expected: <null> but was: <x>;assertNotNull(null)→expected: not <null>
Predict the output
What does the failure say?
The cart holds 2 items. Pick the message JUnit prints.
Round 1 of 3
The expected value comes first.
assertSame versus assertEquals, and why equals() matters
assertSame(expected, actual) passes only when both references point to the same object (==). assertEquals calls expected.equals(actual) instead, so it passes for two different objects with equal values.
Two Price objects can print the same text and still not be equal. See why in plain Java, then in tests that use assertEquals and assertSame.
Example 2 · == versus equals(): a class without equals and a record
class Price { // no equals(): inherits Object.equals, which is == final int rupees;
Price(int rupees) { this.rupees = rupees; }
@Override public String toString() { return "Rs " + rupees; }}
record Money(int rupees) { // records get equals() and hashCode() for free}
public class EqualsDemo { public static void main(String[] args) { Price a = new Price(10); Price b = new Price(10); System.out.println(a + " vs " + b); System.out.println("Price == : " + (a == b)); System.out.println("Price equals : " + a.equals(b));
Money m = new Money(10); Money n = new Money(10); System.out.println("Money == : " + (m == n)); System.out.println("Money equals : " + m.equals(n));
Price same = a; System.out.println("same object ==: " + (a == same)); }}Rs 10 vs Rs 10 Price == : false Price equals : false Money == : false Money equals : true same object ==: true
What this code does
Pricehas noequals(), so two prices of Rs 10 are "not equal":assertEquals(new Price(10), new Price(10))would fail. The recordMoneycompares its fields, soequalsis true while==is still false.==is true only for the very same object (aandsame). That is whatassertSamechecks.
Example 3 · assertEquals needs equals(); assertSame needs the same object
Runs in: a Maven project with JUnit 5 (shoplite-api: src/test/java/com/shoplite/cart)
package com.shoplite.cart;
import static org.junit.jupiter.api.Assertions.assertEquals;import static org.junit.jupiter.api.Assertions.assertNotSame;import static org.junit.jupiter.api.Assertions.assertSame;
import java.math.BigDecimal;import java.util.List;
import org.junit.jupiter.api.Test;
class EqualityTest {
static class Price { // no equals() final int rupees;
Price(int rupees) { this.rupees = rupees; }
@Override public String toString() { return "Rs " + rupees; } }
@Test void recordsAreEqualByValue() { assertEquals(new CartLine("PEN-BLU", new BigDecimal("10.00"), 2), new CartLine("PEN-BLU", new BigDecimal("10.00"), 2)); }
@Test void aClassWithoutEqualsIsOnlyEqualToItself() { assertEquals(new Price(10), new Price(10)); // fails }
@Test void linesReturnsAReadOnlyViewNotTheSameList() { Cart cart = new Cart(); List<CartLine> view = cart.lines();
assertNotSame(view, cart.lines()); // a new view object each call assertSame(view, view); }}[ERROR] Tests run: 3, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 0.052 s <<< FAILURE! -- in com.shoplite.cart.EqualityTest [ERROR] com.shoplite.cart.EqualityTest.aClassWithoutEqualsIsOnlyEqualToItself -- Time elapsed: 0.006 s <<< FAILURE! org.opentest4j.AssertionFailedError: expected: com.shoplite.cart.EqualityTest$Price@37bba400<Rs 10> but was: com.shoplite.cart.EqualityTest$Price@179d3b25<Rs 10>
What this code does
- The failure message is the clue: both values print as
Rs 10, so JUnit adds the class name and an identity code (@37bba400, different on every run) to show they are two different objects. The fix is to givePriceanequals()(or make it a record), not to change the test. Cart.lines()wraps the list in a new read-only view on every call, so two calls give equal content but not the same object;assertNotSamedocuments that.
A class without its own equals() inherits Object.equals, which is just ==. Then assertEquals(new Price(10), new Price(10)) fails even though both print Rs 10. Records, String, Integer, BigDecimal and the collections define equals() for you; your own classes may not.
Use assertSame only when identity matters, such as "the cache returns the very same object".
Find the bug
Find the cause of the failure
Tap the line that causes each failure.
Both prices print Rs 10, yet assertEquals(new Price(10), new Price(10)) fails.
Comparing doubles with a delta and BigDecimal with compareTo
Scale is the number of digits after the decimal point of a BigDecimal: 2.5 has scale 1 and 2.50 has scale 2. BigDecimal.equals compares the value and the scale, so 2.5 and 2.50 are not equal, while compareTo ignores the scale.
Two traps in one program: a double sum is slightly off, and BigDecimal amounts with different decimals are not equal.
Example 4 · double rounding and BigDecimal scale
import java.math.BigDecimal;
public class MoneyCompareDemo { public static void main(String[] args) { double sum = 0.1 + 0.2; System.out.println("0.1 + 0.2 = " + sum); System.out.println("== 0.3 : " + (sum == 0.3)); System.out.println("within 0.000001 : " + (Math.abs(0.3 - sum) <= 0.000001));
BigDecimal a = new BigDecimal("2.5"); BigDecimal b = new BigDecimal("2.50"); System.out.println("2.5 equals 2.50 : " + a.equals(b)); System.out.println("2.5 compareTo 2.50 : " + a.compareTo(b));
BigDecimal lineTotal = new BigDecimal("499.00").multiply(BigDecimal.valueOf(3)); System.out.println("499.00 x 3 : " + lineTotal + " (scale " + lineTotal.scale() + ")"); System.out.println("equals 1497 : " + lineTotal.equals(new BigDecimal("1497"))); System.out.println("equals 1497.00 : " + lineTotal.equals(new BigDecimal("1497.00"))); }}0.1 + 0.2 = 0.30000000000000004 == 0.3 : false within 0.000001 : true 2.5 equals 2.50 : false 2.5 compareTo 2.50 : 0 499.00 x 3 : 1497.00 (scale 2) equals 1497 : false equals 1497.00 : true
What this code does
- A
doublecannot store 0.1 or 0.2 exactly, so their sum is a tiny bit off and==fails. Checking that the difference is within a small delta is whatassertEquals(0.3, sum, 0.000001)does. BigDecimal.equalscompares scale too:2.5is not equal to2.50, and 499.00 × 3 has scale 2, so only1497.00equals it.compareToignores scale and returns 0 for the same amount.
Example 5 · Money assertions that do not lie
Runs in: a Maven project with JUnit 5 (shoplite-api: src/test/java/com/shoplite/cart)
package com.shoplite.cart;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.math.BigDecimal;
import org.junit.jupiter.api.Test;
class MoneyAssertionsTest {
@Test void averageRatingIsCloseToFourPointThree() { double average = (4 + 4 + 5) / 3.0; // 4.333...
assertEquals(4.33, average, 0.01); }
@Test void totalWithTheSameScale() { Cart cart = new Cart(); cart.add("BK-CLEAN", new BigDecimal("499.00"), 3);
assertEquals(new BigDecimal("1497.00"), cart.total()); // scale is part of the check }
@Test void totalComparedByValue() { Cart cart = new Cart(); cart.add("BK-CLEAN", new BigDecimal("499.00"), 3);
assertEquals(0, new BigDecimal("1497").compareTo(cart.total())); }
@Test void wrongScaleFails() { assertEquals(new BigDecimal("2.5"), new BigDecimal("2.50")); }}[ERROR] Tests run: 4, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 0.049 s <<< FAILURE! -- in com.shoplite.cart.MoneyAssertionsTest [ERROR] com.shoplite.cart.MoneyAssertionsTest.wrongScaleFails -- Time elapsed: 0.004 s <<< FAILURE! org.opentest4j.AssertionFailedError: expected: <2.5> but was: <2.50>
What this code does
- The delta version of
assertEqualsis fordoublevalues such as an average rating; never usedoublefor rupees. - For
BigDecimal, choose on purpose:assertEqualswith the full scale when the scale matters, orcompareTo(...) == 0when only the amount matters. A failure likeexpected: <2.5> but was: <2.50>always means a scale mismatch. The AssertJ lesson shows the shorterisEqualByComparingTo.
A double stores most decimals approximately, so 0.1 + 0.2 is 0.30000000000000004. A delta is the largest difference you accept: assertEquals(0.3, 0.1 + 0.2, 0.000001) passes.
Money in ShopLite is BigDecimal. Write the expected value with the same scale as the result (new BigDecimal("230.00")), or compare by value with compareTo, which returns 0 when the amounts are equal: assertEquals(0, expected.compareTo(actual)).
Fix the error
Fix the money and double checks
Read the failure, then pick the line that fixes the test.
Round 1 of 2
The cart total is right, but the test fails.
Error
org.opentest4j.AssertionFailedError: expected: <1497> but was: <1497.00>
assertEquals and the full scale on purpose.assertAll: several failures in one report
assertAll runs every check you pass it as a lambda, even after one fails, and then reports all failures together as a MultipleFailuresError. Use it for several facts that together describe one result.
A cart line has a SKU, a price, a quantity and a total. One test can check all four and still report every wrong field at once.
Example 6 · assertAll and failure messages
Runs in: a Maven project with JUnit 5 (shoplite-api: src/test/java/com/shoplite/cart)
package com.shoplite.cart;
import static org.junit.jupiter.api.Assertions.assertAll;import static org.junit.jupiter.api.Assertions.assertEquals;
import java.math.BigDecimal;
import org.junit.jupiter.api.Test;
class CartLineFieldsTest {
@Test void addingThreeNotebooksMakesOneCorrectLine() { Cart cart = new Cart();
cart.add("NB-A5", new BigDecimal("60.00"), 3);
CartLine line = cart.lines().get(0); assertAll("notebook line", () -> assertEquals("NB-A5", line.sku(), "sku"), () -> assertEquals(new BigDecimal("65.00"), line.unitPrice(), "unit price"), // wrong on purpose () -> assertEquals(3, line.quantity(), "quantity"), () -> assertEquals(new BigDecimal("180.01"), line.lineTotal(), "line total")); // wrong on purpose }}[ERROR] com.shoplite.cart.CartLineFieldsTest.addingThreeNotebooksMakesOneCorrectLine -- Time elapsed: 0.011 s <<< FAILURE! org.opentest4j.MultipleFailuresError: notebook line (2 failures) org.opentest4j.AssertionFailedError: unit price ==> expected: <65.00> but was: <60.00> org.opentest4j.AssertionFailedError: line total ==> expected: <180.01> but was: <180.00>
What this code does
- Without
assertAll, the test would stop at the unit price and you would fix one value, run again, and only then see the line total.assertAllruns all four checks and lists both failures under the headingnotebook line. - The messages
"unit price"and"line total"appear before==>, so each failure says which field it is about, even though several checks compare similar numbers.
Use assertAll when several values together describe one behaviour, such as the fields of one placed order or one cart line. It does not replace small tests: separate rules still belong in separate tests.
Failure messages and message suppliers
Message supplier is a lambda such as () -> "qty of " + sku that JUnit calls only when the assertion fails, to build the failure message. It saves work when the message is expensive to build.
Add a message when the values alone would not say what was checked.
assertEquals(new BigDecimal("1798.00"), cart.total(), "Cart total");// fails: Cart total ==> expected: <1798.00> but was: <1799.00>
assertTrue(product.stock() >= 0, "stock must not be negative");// fails: stock must not be negative ==> expected: <true> but was: <false>
assertEquals(2, line.quantity(), () -> "quantity of " + line.sku() + " in " + cart.lines());// the lambda runs only if the assertion failsEvery assertion takes an optional last argument: a failure message that JUnit puts in front of the standard text, as in Cart total ==> expected: <1798.00> but was: <1799.00>.
A message supplier is worth it when building the message costs work, such as joining a long list or formatting many values: JUnit builds it only for a failure.
Next step
Check your understanding
11 quick questions