Getting started with JUnit Assertions

Assertions are the core building blocks of unit testing, validating that expected method outputs match actual runtime results in Java applications. The org.junit.jupiter.api.Assertions class in JUnit 5 introduces expressive features like assertAll for grouped assertions, lambda-based lazy message evaluation, and exception verification with assertThrows. In this guide, you will explore practical examples of every major JUnit 5 assertion method.

If an assertion fails, the test is halted at the line of code where the assertion is located, and the assertion failure is reported. If the assertion succeeds, the test continues to the next line of code. JUnit Jupiter, comes with many of assertion methods that JUnit 4 has and adds some overloads which can be used with Java 8 Lambda Expression. Let’s see them in detail:

assertAll

AssertAll can be used to verify a group of conditions. The interesting thing about assertAll is that it always checks all of the assertions that are passed to it, no matter how many fail. If all pass, all is fine – if at least one fails you get a detailed result of all that went wrong.

It is best used for asserting a set of properties that belong together conceptionally. Example: assume you have a simple class like an address with fields city, street, number and would like to assert that those are what you expect them to be:

Address address = addressFactory.buildAddress();
assertEquals("New York", address.getCity());
assertEquals("Park avenue", address.getStreet());
assertEquals("1250", address.getNumber());

Now, as soon as the first assertion fails, you will never see the results of the second, which can be an issue. Using assertAll can be the right approach. Indeed, if the method returns the wrong address, you will still see the following error stack trace:

(3 failures)
    expected: <New York> but was: <Philadelphia>
    expected: <Park avenue> but was: <street 51>
    expected: <1250> but was: <126>

Please notice that you coule use also the lamda syntax as well:

Address address = addressFactory.buildAddress();
assertAll("Checking full address",
    () -> assertEquals("New York", address.getCity()),
    () -> assertEquals("Park avenue", address.getStreet()),
    () -> assertEquals("1250", address.getNumber())

assertNull

Asserts that an object is null. If it isn’t an AssertionError is thrown:

 @Test
  public void testWithNull() {
     
    Integer year = null;     
    assertNull(year, "The year is not null");
   
}

assertNotNull

Asserts that an object is not null. If it isn’t an AssertionError is thrown:

 @Test
  public void testWithNull() {
     
    Integer year = 2019;     
    assertNotNull(year, "The year is not null");
   
}

assertThrows

An expected exception is considered to be just another condition that can be asserted, and thus Assertions contains methods to handle this. Example:

@Test()
@DisplayName("Empty argument")
public void testAdd_ZeroOperands_EmptyArgument() {
  long[] numbersToSum = {};
  assertThrows(IllegalArgumentException.class, () ‑> classUnderTest.add(numbersToSum));
}

 @Test
  public void testIsNullOrBlankOK() {
    // Test the case that the input is NULL
    String input = null;

    assertTrue(StringUtils.isNullOrBlank(input));
  
    // Test case with the input is empty
    input = " ";
    assertTrue(StringUtils.isNullOrBlank(input));

    // Test case with the input is not empty
    input = "abc";

    assertFalse(StringUtils.isNullOrBlank(input));

  }

assertSame and assertNotSame

assertSame checks the object reference using the == operator. Here is an example:

BigDecimal b1 = new BigDecimal("500");
BigDecimal b2 = new BigDecimal("500");
BigDecimal b3 = b1;
 
int i1 = 10;
int i2 = 10;
 
  @Test
  public void BigDecimaltest() throws Exception {
    // if(b1 == b2)
    assertSame(b1, b2);    // FAILS!
 
    // b1.equals(b2)
    assertEquals(b1, b2);  // PASSES!
 
    // (b1 == b3)
    assertSame(b1, b3);    // PASSES!
 
    //(b1.equals(b3))
    assertEquals(b1, b3);  // PASSES!
  }


    assertNotSame(defaultSt, actual, () -> "Expected ouput is same with actual");

assertEquals

Check two objects/primitive values using the following rule:

  • If primitive values are passed and then the values are compared.
  • If objects are passed, then the equals() method is invoked.
  @Test
  public void testConcatWithRegularInput() {
    String st1 = "Hello";
    String st2 = "World";
    String st3 = "!";
    String expect = st1 + st2 + st3;
    String actual = StringUtils.concat(st1, st2, st3);
    assertEquals(expect, actual);
}

What is the difference between assertions and assumptions? The difference can be subtle, so use this rule of thumb: Use assertions to check the results of a test method. Use assumptions to determine whether to run the test method at all. An aborted test is not reported as a failure, meaning that failure won’t break the build.

 

 

Common Problems & Solutions

Problem: Floating-point comparison assertions (double/float) fail unexpectedly.
Cause: Floating-point precision issues in Java binary arithmetic.
Solution: Always specify a delta threshold, e.g., assertEquals(4.0, result, 0.001).

Problem: Standard assertions stop evaluating after the first failure, obscuring other broken properties.
Cause: Standard assertions halt test execution immediately upon failure.
Solution: Group related property checks inside assertAll() so all assertions are executed and reported together.


Recommended Articles

JUnit 5 Cheatsheet: Essential Tips for Java Developers

Master JUnit 5 Jupiter Tests with our comprehensive cheatsheet. Learn about lifecycle, assertions, and conditional execution in Java.

How to Assert No Exception Thrown in Java with JUnit 4 and JUnit 5

Learn how to assert no exception thrown in Java tests using JUnit 4 and JUnit 5. #Java #JUnit #Testing #CloudNative

Mastering Mockito for Java Applications: Plugging into JUnit and Quarkus Tests

Learn how to integrate Mockito in JUnit and Quarkus tests for effective unit testing. #Mockito #JavaTesting #JUnit #Quarkus

Maximize Test Efficiency with JUnit AssertTimeout: A Comprehensive Guide

Learn how to implement timeout assertions in JUnit tests to ensure timely test execution and prevent lengthy tests from running indefinitely.