Skip to content
  • About Us
  • Contact Us
  • Disclaimer
  • Privacy Policy
  • Terms and Conditions

Simplified Learning Blog

Learning made easy

  • Java
    • Core Java Tutorial
    • Java 8
    • What is Rest API in java
    • Spring Framework
    • Type Casting in Java | 2 types Implicit and explicit casting
    • Spring Boot Tutorial
      • Spring Boot Rest API Example complete guide
    • Top 50 Java Interview Questions
    • JUnit 5 Tutorial
      • Assertall in JUnit 5
      • Assertions in JUnit 5
    • Java Thread Tutorials
      • How to create thread in Java
      • Multithreading in java
      • Daemon Thread in Java | How to create daemon thread in java
      • Top 40+ Multithreading interview questions
  • AWS
    • What is AWS (Amazon Web Services)
    • AWS IAM (Identity and Access Management)
    • AWS SNS | What is SNS
    • What is SQS | AWS SQS (Simple Queue Service)
    • What is AWS Lambda
    • Top 10 AWS Lambda interview questions
  • Java Codes
  • Software Architecture
    • Software Architecture Performance
    • Performance Principles of Software Architecture
    • System Performance Objective
  • Spring Boot Tutorial
  • Tools
    • JSON Formatter and Validator
  • Tech Blogs
    • Java 21 New Features
    • Is Java Dead? Is java dead, 2023 ?
    • New Features in Java 17
  • Toggle search form

Assertions in JUnit 5

Posted on February 9, 2023April 5, 2023 By Admin No Comments on Assertions in JUnit 5

Assertions:

Assertions in JUnit 5 Assertions are a set of methods present in Junit 5 Assert Class which is used in asserting various conditions in tests.

Table of Contents

Toggle
  • Assertions:
    • JUnit 5 Assertions
    • JUnit 5 Assertions methods
  • How to Utilize Assertions Effectively
    • Example 1: Test Cases Using JUnit 5 Assertions
    • Example 2: Testing the Division of Two Numbers
    • Example 3: Testing for Null Values
  • Conclusion
  • FAQ
    • What is the Difference Between JUnit 4 and JUnit 5?
    • What are some best practices for writing unit tests?
    • How Can I Run JUnit Tests in My IDE?
    • What are some popular testing frameworks for Java?
    • How can I improve the performance of my unit tests?

While using assertion, we are going to import this asserts class as static import, and then we will call its methods.

JUnit 5 Assertions

In Assert JUnit 5 we still have the lot of methods from JUnit 4 and few newer methods as well which follow Java 8 in implementation. You can do assertions on all primitive type, Objects and Array type.

With Java 8 support, the output message can be a supplier, allowing lazy evaluation.

Let’s see the available assertions that we can use:

JUnit 5 Assertions methods

  1. assertArrayEquals: It verifies the equality of arrays.
  2. assertEquals: If we need to assert two values, we can use assertEquals. It also supports diff between the two, and for that we need to pass an additional delta parameter.
  3. assertTrue: It is used to assert the true statement.
  4. assertFalse: It is used to assert the false statement. For both assert true and false, we can use boolean supplier provided by java8 instead of boolean condition.
  5. assertSame and assertNotSame: It is used to assert that the actual and expected refer to the same object and not same in assertNotSame case.
  6. assertNull and assertNotNull: it is used to assert null and non-null values.

7. fail: fail assertion fails the test case, used in case of test cases half cooked that means in development stage like in case of TDD (Test Driven Development) approach we can use it.

8. assertAll: assert all is used in case of grouping the assertions and their results are reported together.

9. assertNotEquals: Used to check non-equality of expected and actual values.

10. assertThrows: Used to assert the thrown exception

Let’s see all of these one by one


package com.slb.core.unittest;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.*;

public class AssertionsDemo {

    @Test
    public void whenAssertingEquality() {

        String expected = "SLB";
        String actual = "SLB";

        Assertions.assertEquals(expected, actual);
    }

    @Test
    public void whenAssertingNonEquality() {
        String expected = "SLB";
        String actual = "Simplified Learning Blog";

        Assertions.assertNotEquals(expected, actual);
    }

    @Test
    public void whenAssertingArraysEquality() {
        char[] expected = {'J','A','V','A','8'};
        char[] actual = "JAVA8".toCharArray();

        assertArrayEquals(expected, actual);
    }

    @Test
    public void whenAssertingNotSameObject() {
        Object ram = new Object();
        Object shyam = new Object();

        assertNotSame(ram, shyam);
    }
    @Test
    public void whenAssertingSameObject() {
        Object ram = new Object();
        Object rahul = ram;

        assertSame(ram, rahul);
    }
    @Test
    public void whenAssertingTrueConditions() {
        assertTrue( 100 > 10);
    }
    @Test
    public void whenAssertingFalseConditions() {
        assertFalse( 5 > 6);
    }
//    @Test
//    public void whenAssertingTriggersFail() {
//        fail("Exception scenario");
//    }

    @Test
    public void testAssertThat() {
        assertAll( "asserting all", ( () -> assertTrue( 5 > 4) ), () -> assertFalse( 3 > 4) );

    }
    @Test
    void whenAssertingException_thenThrown() {
        Throwable exception = assertThrows(
                ArithmeticException.class,
                () -> {
                    throw new ArithmeticException("Exception message");
                }
        );
        assertEquals("Exception message", exception.getMessage());
    }
}

All of the above code is available at SLB GitHub

How to Utilize Assertions Effectively

When writing unit tests, it’s essential to utilize assertions correctly. Here are some tips for crafting effective assertions in JUnit 5:

  1. Be Specific
    Make sure your assertions are specific and related to the behavior you are testing. Steer clear of making generalizations that may not apply in this particular instance.
  2. Include Descriptive Messages
    Include descriptive messages with your assertions to make it obvious what is being tested and why. Doing this can be especially useful when a test fails, as it helps identify the issue quickly.
  3. Validate Positive and Negative Cases
    It is essential to test both positive and negative cases for each behavior being tested, in order to guarantee that your code behaves as expected in all scenarios. Doing this will help guarantee that the code works as expected across all scenarios.
  4. Minimize Assertion Clutter
    Be mindful when including too many assertions in one test method. Doing so may make the test hard to read and comprehend, potentially making it more difficult to pinpoint why a failure occurred.
  5. Select the Appropriate Assertion Type
    Select the correct assertion type for testing a condition. For instance, assertEquals() can be used when comparing two objects for equality and assertNull() can be used when testing for null values.

Example 1: Test Cases Using JUnit 5 Assertions

Let’s take a look at some example test cases that use JUnit 5 assertions.

@Test
void testAddition() {
    Calculator calculator = new Calculator();
    int result = calculator.add(12, 3);
    assertEquals(15, result, "Addition of two numbers should return the correct sum.");
}

In this above example, we are testing the addition of two numbers using the assertEquals() assertion method. The test passes if the result of the addition is equal to the expected value of 15, otherwise it will fail.

Example 2: Testing the Division of Two Numbers

@Test
void testDivision() {
    Calculator calculator = new Calculator();
    double result = calculator.divide(100, 2);
    assertEquals(50, result);
}

In this example, we are testing the division of two numbers using the assertEquals() assertion method. If the result of the division equals 50 as expected, then our test passes.

Example 3: Testing for Null Values

@Test
void testNullValue() {
    MyTestClass myTestClass = new MyTestClass ();
    assertNull(myTestClass.getProperty(), "Property should be null.");
}

In this example, we are testing that a property in the MyTestClass object is null using the assertNull() assertion method. If the property is null, then our test passes.

Conclusion

Assertions in JUnit 5 are an integral component of writing successful unit tests in Java. By using specific and targeted assertions, providing descriptive messages, and testing both positive and negative cases alike, you can ensure your code behaves as expected under all circumstances. With a wide selection of assertion methods at your disposal, you have the flexibility to test various conditions and scenarios with confidence.

FAQ

What is the Difference Between JUnit 4 and JUnit 5?

JUnit 5 introduced many new features and improvements from its predecessor, such as support for Java 8 or later, parameterized tests, and enhanced extension capabilities.

What are some best practices for writing unit tests?

Some recommended practices when crafting unit tests include writing specific and targeted tests, using descriptive names for both tests and methods, testing both positive and negative cases, and efficiently using assertions.

How Can I Run JUnit Tests in My IDE?

Most IDEs provide support for running JUnit tests out-of-the-box. You usually right-click a test class or method and select either “Run” or “Run as JUnit test”.

What are some popular testing frameworks for Java?

Popular options include TestNG, Mockito and AssertJ.

How can I improve the performance of my unit tests?

You can boost performance by minimizing external resources like databases or network connections, using mocking frameworks to simulate dependencies, and running tests in parallel.

Previous Topic: JUnit 5

Related

Java

Post navigation

Previous Post: JUnit 5 Tutorial
Next Post: What is Rest API in java

More Related Articles

Assertall in JUnit 5 Java
What is Rest API in java Java
Top 50 Java Coding Interview Questions and Answers (2025 Updated) Java
Type Casting in Java | 2 types Implicit and explicit casting Java
JUnit 5 Tutorial Java
Java Text Blocks Java

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Recent Posts

  • Top 50 Java Coding Interview Questions and Answers (2025 Updated)
  • Java Record Class Explained: Simple, Immutable Data Carriers
  • Java Convert int to String – 5+ Methods with Examples
  • String to Integer Conversion in Java | Java convert string to int
  • PDF to JSON Convertor

Recent Comments

No comments to show.

Copyright © 2025 Simplified Learning Blog.

Powered by PressBook Green WordPress theme