JUnit Assertions
JUnit assertions are the methods that decide whether a test passes or fails. Each one compares what your code actually did with what you expected, and if they differ, it throws an AssertionFailedError that stops the test and reports both values.
This lesson covers every assertion you will use in JUnit 6: assertEquals, assertTrue, assertNull, assertSame, the array and collection assertions, assertThrows, assertAll, assertTimeout, assertInstanceOf and fail. Each section shows a passing example and the exact failure message you get when it breaks. If you have not written a test yet, start with Java JUnit Basics, and see JUnit Test Methods for the annotations used around these assertions.
How JUnit Assertions Work
All assertions are static methods of the class org.junit.jupiter.api.Assertions. Most tests import them with a static import so you can write assertEquals(...) instead of Assertions.assertEquals(...).
import static org.junit.jupiter.api.Assertions.*;
When an assertion holds, nothing happens and the test continues. When it does not hold, JUnit throws an exception, the rest of the test method is skipped, and the test is reported as failed.
| Assertion | Passes when |
|---|---|
assertEquals(expected, actual) | expected.equals(actual) (or == for primitives) |
assertNotEquals(unexpected, actual) | The values are not equal |
assertTrue(condition) / assertFalse(condition) | The condition is true / false |
assertNull(value) / assertNotNull(value) | The value is / is not null |
assertSame(expected, actual) | Both refer to the same object (==) |
assertArrayEquals(expected, actual) | Arrays have equal elements in the same order |
assertIterableEquals(expected, actual) | Iterables have equal elements in the same order |
assertThrows(type, executable) | The code throws type or a subclass |
assertDoesNotThrow(executable) | The code throws nothing |
assertAll(executables...) | Every grouped assertion passes |
assertTimeout(duration, executable) | The code finishes within the duration |
assertInstanceOf(type, value) | The value is an instance of type |
fail(message) | Never: it always fails |
Every assertion also accepts an optional message as its last argument, either a String or a Supplier<String>.
assertEquals and assertNotEquals
assertEquals is the assertion you will write most often. Always pass the expected value first and the actual value second, because JUnit uses that order in the failure message.
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import org.junit.jupiter.api.Test;
class PriceCalculatorTest {
int totalInRupees(int unitPrice, int quantity) {
return unitPrice * quantity;
}
@Test
void multipliesPriceByQuantity() {
assertEquals(1497, totalInRupees(499, 3));
}
@Test
void differentQuantitiesGiveDifferentTotals() {
assertNotEquals(totalInRupees(499, 2), totalInRupees(499, 3));
}
@Test
void showsAFailureMessage() {
assertEquals(1500, totalInRupees(499, 3), "total for 3 books");
}
}
Output for the third test:
org.opentest4j.AssertionFailedError: total for 3 books ==> expected: <1500> but was: <1497>
How it works:
- The first two tests pass silently.
- In the failing test, the message
total for 3 booksis printed before==>, followed by the expected and actual values. - For objects,
assertEqualscallsequals(). TwoStringobjects with the same text are equal even if they are different objects.
Comparing double and float Values With a Delta
Floating-point arithmetic is not exact. 0.1 + 0.2 is 0.30000000000000004, so comparing it with 0.3 fails. Pass a third argument, the delta, to allow a small difference.
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
class DoubleAssertionTest {
@Test
void exactComparisonFails() {
assertEquals(0.3, 0.1 + 0.2);
}
@Test
void comparisonWithDeltaPasses() {
assertEquals(0.3, 0.1 + 0.2, 0.000001);
}
}
Output for the first test:
org.opentest4j.AssertionFailedError: expected: <0.3> but was: <0.30000000000000004>
How it works:
- Without a delta, JUnit compares the two
doublevalues exactly, so the first test fails. - With a delta of
0.000001, the test passes because the difference is far smaller than that.
Note: For money, avoid
doublealtogether. Uselongpaise orBigDecimaland compare exact values.
assertTrue and assertFalse
Use assertTrue and assertFalse for conditions that are naturally boolean, such as "the list is empty" or "the password is strong".
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
class PasswordRulesTest {
boolean isStrong(String password) {
return password.length() >= 12
&& password.chars().anyMatch(Character::isDigit)
&& password.chars().anyMatch(Character::isUpperCase);
}
@Test
void longPasswordWithDigitAndUppercaseIsStrong() {
assertTrue(isStrong("GoCourse2026Java"));
}
@Test
void shortPasswordIsWeak() {
assertFalse(isStrong("Java1"), "passwords under 12 characters must be weak");
}
@Test
void failingAssertTrue() {
String password = "alllowercase1234";
assertTrue(isStrong(password), () -> "expected strong password but got weak for: " + password);
}
}
Output for the third test:
org.opentest4j.AssertionFailedError: expected strong password but got weak for: alllowercase1234 ==> expected: <true> but was: <false>
How it works:
assertTruepasses only when the condition istrue;assertFalseonly when it isfalse.- A plain
assertTruefailure only saysexpected: <true> but was: <false>, which tells you very little. A message explains what was being checked. - The
Suppliermessage() -> "..." + passwordis built only when the test fails, so it costs nothing for passing tests.
Note: Prefer
assertEquals(3, list.size())overassertTrue(list.size() == 3). The first prints the actual size when it fails; the second only printsfalse.
assertNull and assertNotNull
These check whether a method returned null, for example when a lookup finds nothing.
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import java.util.Map;
import org.junit.jupiter.api.Test;
class CourseLookupTest {
private final Map<String, String> coursesById = Map.of(
"JAVA101", "Java Basics",
"PY101", "Python Basics");
String findTitle(String courseId) {
return coursesById.get(courseId); // null when the id is unknown
}
@Test
void knownIdReturnsTitle() {
String title = findTitle("JAVA101");
assertNotNull(title);
assertEquals("Java Basics", title);
}
@Test
void unknownIdReturnsNull() {
assertNull(findTitle("GO999"));
}
}
Output (mvn test, shortened):
[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0
How it works:
assertNotNullruns first, so iftitleisnullthe test fails with a clear message instead of aNullPointerExceptionlater.assertNullconfirms the "not found" case. If it failed, JUnit would printexpected: <null> but was: <...>with the unexpected value.
assertSame and assertNotSame
assertEquals checks that two objects are equal. assertSame checks that they are the same object in memory, using ==. This matters when testing caches and singletons.
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.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.Test;
class ConfigCacheTest {
private final Map<String, StringBuilder> cache = new HashMap<>();
StringBuilder loadConfig(String name) {
return cache.computeIfAbsent(name, key -> new StringBuilder("config:" + key));
}
@Test
void cacheReturnsTheSameObject() {
StringBuilder first = loadConfig("app");
StringBuilder second = loadConfig("app");
assertSame(first, second);
}
@Test
void equalTextButDifferentObjects() {
String a = new String("gocourse");
String b = new String("gocourse");
assertEquals(a, b); // same text
assertNotSame(a, b); // different objects
}
}
Output (mvn test, shortened):
[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0
How it works:
computeIfAbsentcreates theStringBuilderonce and returns the cached object on the second call, soassertSamepasses.new String(...)always creates a new object. The two strings are equal byequals()but are not the same object, so both assertions in the second test pass.
Assert Arrays and Collections
assertEquals on two arrays compares references, not contents, so it fails even for identical arrays. Use assertArrayEquals for arrays and assertIterableEquals for lists and other iterables.
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertIterableEquals;
import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.Test;
class CollectionAssertionsTest {
@Test
void sortedArrayHasExpectedOrder() {
int[] marks = {72, 45, 98, 60};
Arrays.sort(marks);
assertArrayEquals(new int[] {45, 60, 72, 98}, marks);
}
@Test
void listsWithSameElementsAreEqual() {
List<String> enrolled = List.of("Asha", "Ravi", "Meena");
assertIterableEquals(List.of("Asha", "Ravi", "Meena"), enrolled);
assertEquals(List.of("Asha", "Ravi", "Meena"), enrolled); // List.equals also works
}
@Test
void arrayMismatchShowsTheIndex() {
assertArrayEquals(new int[] {1, 2, 3}, new int[] {1, 2, 4});
}
}
Output for the third test:
org.opentest4j.AssertionFailedError: array contents differ at index [2], expected: <3> but was: <4>
How it works:
assertArrayEqualscompares element by element and reports the first index where the arrays differ.- For lists,
assertEqualsworks too becauseList.equalscompares contents.assertIterableEqualsis useful when the two sides are different iterable types, and it also reports the differing index. - Order matters for both. To compare without order, convert both sides to a
Setfirst.
For lines of text, such as log output, assertLinesMatch compares a list of expected lines where each line may also be a regular expression:
@Test
void logLinesMatch() {
List<String> logLines = List.of("Server started on port 8080", "Loaded 42 courses");
assertLinesMatch(List.of("Server started on port \\d+", "Loaded \\d+ courses"), logLines);
}
This test passes because each actual line either equals or matches the expected pattern. (Import assertLinesMatch from Assertions as well.)
Test Exceptions With assertThrows
assertThrows runs a lambda and passes only if it throws the expected exception type. It returns the exception, so you can also check its message.
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertThrowsExactly;
import org.junit.jupiter.api.Test;
class AgeValidatorTest {
int parseAge(String input) {
int age = Integer.parseInt(input.strip());
if (age < 0 || age > 150) {
throw new IllegalArgumentException("Age out of range: " + age);
}
return age;
}
@Test
void negativeAgeIsRejected() {
IllegalArgumentException error =
assertThrows(IllegalArgumentException.class, () -> parseAge("-5"));
assertEquals("Age out of range: -5", error.getMessage());
}
@Test
void textInputThrowsNumberFormatException() {
// NumberFormatException is a subclass of IllegalArgumentException
assertThrows(IllegalArgumentException.class, () -> parseAge("twenty"));
assertThrowsExactly(NumberFormatException.class, () -> parseAge("twenty"));
}
@Test
void validAgeDoesNotThrow() {
int age = assertDoesNotThrow(() -> parseAge(" 27 "));
assertEquals(27, age);
}
@Test
void failsWhenNothingIsThrown() {
assertThrows(IllegalArgumentException.class, () -> parseAge("30"));
}
}
Output for the fourth test:
org.opentest4j.AssertionFailedError: Expected java.lang.IllegalArgumentException to be thrown, but nothing was thrown.
How it works:
assertThrowsaccepts the given type or any subclass, soNumberFormatExceptionsatisfiesIllegalArgumentException.class.assertThrowsExactlyaccepts only that exact class, which is stricter.assertDoesNotThrowreturns the lambda's result, so you can check it in the next line.- If the lambda finishes normally,
assertThrowsfails with the message above.
Group Assertions With assertAll
Normally a test stops at the first failed assertion, so you only see one problem at a time. assertAll runs every assertion in the group and reports all failures together.
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
class StudentProfileTest {
record Student(String name, String email, int age, boolean active) {}
Student loadStudent() {
return new Student("asha", "asha@example.com", 21, false);
}
@Test
void profileHasCorrectFields() {
Student student = loadStudent();
assertAll("student profile",
() -> assertEquals("Asha", student.name(), "name"),
() -> assertEquals("asha@example.com", student.email(), "email"),
() -> assertEquals(21, student.age(), "age"),
() -> assertTrue(student.active(), "active"));
}
}
Output:
org.opentest4j.MultipleFailuresError: student profile (2 failures)
org.opentest4j.AssertionFailedError: name ==> expected: <Asha> but was: <asha>
org.opentest4j.AssertionFailedError: active ==> expected: <true> but was: <false>
How it works:
- Each assertion is wrapped in a lambda, so
assertAllcan run them one after another and collect failures. - The report shows both problems at once: the name is lowercase and the student is inactive. Without
assertAll, you would fix the name, rerun, and only then discover the second problem. - The heading
student profilelabels the group in the report.
Check Execution Time With assertTimeout
assertTimeout fails if a block of code takes longer than a given Duration. It is useful for code with a performance promise, such as a search that must answer quickly.
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTimeout;
import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
import java.time.Duration;
import org.junit.jupiter.api.Test;
class SearchSpeedTest {
String slowSearch(String keyword, long delayMillis) throws InterruptedException {
Thread.sleep(delayMillis);
return "Results for " + keyword;
}
@Test
void fastSearchFinishesInTime() {
String result = assertTimeout(Duration.ofMillis(500), () -> slowSearch("java", 50));
assertEquals("Results for java", result);
}
@Test
void slowSearchWaitsThenFails() {
assertTimeout(Duration.ofMillis(100), () -> slowSearch("java", 400));
}
@Test
void slowSearchIsAbortedEarly() {
assertTimeoutPreemptively(Duration.ofMillis(100), () -> slowSearch("java", 5_000));
}
}
Output for the second and third tests (numbers vary slightly):
org.opentest4j.AssertionFailedError: execution exceeded timeout of 100 ms by 302 ms
org.opentest4j.AssertionFailedError: execution timed out after 100 ms
How it works:
assertTimeoutlets the code finish, then fails if it took too long. The second test waits the full 400 ms before reporting.assertTimeoutPreemptivelyruns the code in a separate thread and stops waiting as soon as the limit is reached, so the third test fails after about 100 ms instead of 5 seconds.- Both return the block's result, as the first test shows.
Note: Because
assertTimeoutPreemptivelyruns code in another thread, anything that relies on the current thread, such asThreadLocalvalues or Spring transactions, may behave differently inside it. Use the plainassertTimeoutwhen in doubt.
assertInstanceOf and fail
assertInstanceOf checks the runtime type of a value and returns it already cast, which saves a manual cast. fail fails a test unconditionally, which is useful in branches that should never be reached.
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.fail;
import org.junit.jupiter.api.Test;
class PaymentTypeTest {
sealed interface Payment permits CardPayment, UpiPayment {}
record CardPayment(String lastFourDigits) implements Payment {}
record UpiPayment(String upiId) implements Payment {}
Payment parse(String input) {
return input.contains("@") ? new UpiPayment(input) : new CardPayment(input.substring(input.length() - 4));
}
@Test
void upiIdIsParsedAsUpiPayment() {
UpiPayment upi = assertInstanceOf(UpiPayment.class, parse("asha@okbank"));
assertEquals("asha@okbank", upi.upiId());
}
@Test
void everyPaymentTypeIsHandled() {
Payment payment = parse("4111111111111111");
switch (payment) {
case CardPayment card -> assertEquals("1111", card.lastFourDigits());
case UpiPayment upi -> fail("A card number must not be parsed as UPI: " + upi);
}
}
}
Output (mvn test, shortened):
[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0
How it works:
assertInstanceOf(UpiPayment.class, ...)passes and returns the value typed asUpiPayment, soupi.upiId()compiles without a cast.- If the type were wrong, it would fail with
Unexpected type, expected: <...UpiPayment> but was: <...CardPayment>. - In the second test, the
UpiPaymentbranch should never run for a card number.fail(...)makes the test fail with a clear message if it ever does.
Real-World Example: Testing a Shopping Cart With JUnit Assertions
This example tests a small shopping cart using most of the assertions from this lesson.
package com.gocourse.shop;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class ShoppingCart {
public record Item(String sku, String name, long priceInPaise, int quantity) {}
private final List<Item> items = new ArrayList<>();
private String couponCode;
public void add(Item item) {
if (item.quantity() <= 0) {
throw new IllegalArgumentException("Quantity must be positive for " + item.sku());
}
items.add(item);
}
public void applyCoupon(String code) {
if (!code.equals("GOCOURSE10")) {
throw new IllegalStateException("Unknown coupon: " + code);
}
this.couponCode = code;
}
public long totalInPaise() {
long subtotal = items.stream().mapToLong(i -> i.priceInPaise() * i.quantity()).sum();
return couponCode == null ? subtotal : subtotal - subtotal / 10;
}
public List<Item> items() {
return Collections.unmodifiableList(items);
}
public String couponCode() {
return couponCode;
}
}
package com.gocourse.shop;
import static org.junit.jupiter.api.Assertions.*;
import com.gocourse.shop.ShoppingCart.Item;
import java.util.List;
import org.junit.jupiter.api.Test;
class ShoppingCartTest {
private final Item javaBook = new Item("BK-1", "Java Book", 49_900, 2);
private final Item keyboard = new Item("KB-7", "Keyboard", 129_900, 1);
@Test
void newCartIsEmpty() {
ShoppingCart cart = new ShoppingCart();
assertAll("empty cart",
() -> assertTrue(cart.items().isEmpty()),
() -> assertEquals(0, cart.totalInPaise()),
() -> assertNull(cart.couponCode()));
}
@Test
void totalAddsPriceTimesQuantity() {
ShoppingCart cart = new ShoppingCart();
cart.add(javaBook);
cart.add(keyboard);
assertEquals(229_700, cart.totalInPaise(), "2 x 499.00 + 1 x 1299.00");
assertIterableEquals(List.of(javaBook, keyboard), cart.items());
}
@Test
void couponTakesTenPercentOff() {
ShoppingCart cart = new ShoppingCart();
cart.add(keyboard);
cart.applyCoupon("GOCOURSE10");
assertAll("discounted cart",
() -> assertEquals("GOCOURSE10", cart.couponCode()),
() -> assertEquals(116_910, cart.totalInPaise()));
}
@Test
void invalidInputIsRejected() {
ShoppingCart cart = new ShoppingCart();
IllegalArgumentException badQuantity = assertThrows(IllegalArgumentException.class,
() -> cart.add(new Item("BK-1", "Java Book", 49_900, 0)));
assertEquals("Quantity must be positive for BK-1", badQuantity.getMessage());
IllegalStateException badCoupon = assertThrows(IllegalStateException.class,
() -> cart.applyCoupon("FREE100"));
assertTrue(badCoupon.getMessage().contains("FREE100"));
}
@Test
void itemsListCannotBeModifiedFromOutside() {
ShoppingCart cart = new ShoppingCart();
cart.add(javaBook);
assertThrows(UnsupportedOperationException.class, () -> cart.items().clear());
assertEquals(1, cart.items().size());
}
@Test
void largeCartIsTotalledQuickly() {
ShoppingCart cart = new ShoppingCart();
for (int i = 0; i < 10_000; i++) {
cart.add(new Item("SKU-" + i, "Item " + i, 100, 1));
}
long total = assertTimeout(java.time.Duration.ofMillis(200), cart::totalInPaise);
assertEquals(1_000_000, total);
}
}
Output of mvn test (shortened):
[INFO] Running com.gocourse.shop.ShoppingCartTest
[INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.061 s -- in com.gocourse.shop.ShoppingCartTest
[INFO] BUILD SUCCESS
How it works:
- Empty state.
newCartIsEmptyusesassertAllso that, if several defaults were wrong, you would see all of them in one run. - Exact money values. Prices are
longpaise, soassertEquals(229_700, ...)compares exact numbers with no delta. The message documents how the total was calculated. - Order of items.
assertIterableEqualsconfirms the cart keeps items in the order they were added. - The discount rule. 1,299.00 minus 10 % is 1,169.10, which is
116_910paise. Grouping it with the coupon check shows both the stored code and the total. - Errors and messages.
assertThrowsreturns each exception, so the test also checks that the messages name the bad SKU and the bad coupon. - Encapsulation. Calling
clear()on the returned list must throwUnsupportedOperationException, and the cart must still hold its item afterwards. - Performance.
assertTimeoutreturns the total, so the same line checks both speed and correctness.
The next lesson, JUnit Test Fixtures, shows how to remove the repeated new ShoppingCart() lines with @BeforeEach.