JUnit assertDoesNotThrow Method

The assertDoesNotThrow method in JUnit is used to assert that a block of code does not throw any kind of exception. JUnit provides several overloaded versions of this method to handle different scenarios and to provide custom messages for test failures. This guide covers the basics of using the assertDoesNotThrow method, including its syntax and examples of its different overloads.

Table of Contents

  1. Introduction
  2. assertDoesNotThrow Method Syntax
  3. Examples
    • Basic Usage
    • Using a Custom Message
    • Using a Message Supplier
    • Returning a Value
  4. Real-World Use Case
  5. Conclusion

Introduction

The assertDoesNotThrow method in JUnit is an assertion method used to verify that a given piece of code does not throw any exception. If the code throws an exception, the assertion fails, and the test is marked as failed. This method is fundamental for writing unit tests that ensure certain operations complete without errors.

assertDoesNotThrow Method Syntax

Here is the basic syntax of the assertDoesNotThrow method with its different overloads:

// Asserts that execution of the supplied executable does not throw any kind of exception
static void assertDoesNotThrow(Executable executable);

// Asserts that execution of the supplied executable does not throw any kind of exception with a custom message
static void assertDoesNotThrow(Executable executable, String message);

// Asserts that execution of the supplied executable does not throw any kind of exception with a custom message supplier
static void assertDoesNotThrow(Executable executable, Supplier<String> messageSupplier);

// Asserts that execution of the supplied supplier does not throw any kind of exception and returns the value
static <T> T assertDoesNotThrow(ThrowingSupplier<T> supplier);

// Asserts that execution of the supplied supplier does not throw any kind of exception with a custom message and returns the value
static <T> T assertDoesNotThrow(ThrowingSupplier<T> supplier, String message);

// Asserts that execution of the supplied supplier does not throw any kind of exception with a custom message supplier and returns the value
static <T> T assertDoesNotThrow(ThrowingSupplier<T> supplier, Supplier<String> messageSupplier);

Parameters:

  • executable: The block of code to be executed.
  • message: Optional. A custom message to display if the assertion fails.
  • messageSupplier: Optional. A supplier that provides a custom message to display if the assertion fails.
  • supplier: A supplier that provides the value to be returned and checked for exceptions.

Returns:

  • The value returned by the supplier, if no exception is thrown.

Examples

Basic Usage

Verify that a block of code does not throw any exception.

Example

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

public class CalculatorTest {
    @Test
    void testAdditionDoesNotThrow() {
        assertDoesNotThrow(() -> {
            int result = 2 + 3;
        });
    }
}

Using a Custom Message

Include a custom message to display if the assertion fails.

Example

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

public class CustomMessageTest {
    @Test
    void testAdditionDoesNotThrowWithMessage() {
        assertDoesNotThrow(() -> {
            int result = 2 + 3;
        }, "Addition should not throw an exception");
    }
}

Using a Message Supplier

Use a message supplier to lazily generate a custom message if the assertion fails.

Example

import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import org.junit.jupiter.api.Test;
import java.util.function.Supplier;

public class MessageSupplierTest {
    @Test
    void testAdditionDoesNotThrowWithMessageSupplier() {
        Supplier<String> messageSupplier = () -> "Addition should not throw an exception";
        assertDoesNotThrow(() -> {
            int result = 2 + 3;
        }, messageSupplier);
    }
}

Returning a Value

Verify that a block of code does not throw any exception and return the value.

Example

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

public class ReturnValueTest {
    @Test
    void testAdditionDoesNotThrowAndReturnValue() {
        int result = assertDoesNotThrow(() -> {
            return 2 + 3;
        });
        assertEquals(5, result);
    }
}

Using a Custom Message with Return Value

Include a custom message to display if the assertion fails and return the value.

Example

import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;

public class ReturnValueWithMessageTest {
    @Test
    void testAdditionDoesNotThrowWithMessageAndReturnValue() {
        int result = assertDoesNotThrow(() -> {
            return 2 + 3;
        }, "Addition should not throw an exception");
        assertEquals(5, result);
    }
}

Real-World Use Case

Testing a UserService Class

A common use case for assertDoesNotThrow is testing methods of a UserService class to ensure that certain operations complete without throwing exceptions.

Class Under Test – UserService

import java.util.HashSet;
import java.util.Set;

public class UserService {
    private Set<String> users = new HashSet<>();

    public boolean addUser(String username) {
        return users.add(username);
    }

    public boolean userExists(String username) {
        return users.contains(username);
    }

    public boolean removeUser(String username) {
        return users.remove(username);
    }
}

Test Class – UserServiceTest

import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;

public class UserServiceTest {
    private final UserService userService = new UserService();

    @Test
    void testAddUserDoesNotThrow() {
        assertDoesNotThrow(() -> {
            userService.addUser("john_doe");
        }, "Adding a user should not throw an exception");
    }

    @Test
    void testRemoveUserDoesNotThrow() {
        userService.addUser("john_doe");
        assertDoesNotThrow(() -> {
            userService.removeUser("john_doe");
        }, "Removing a user should not throw an exception");
    }

    @Test
    void testUserExistsDoesNotThrowAndReturnValue() {
        userService.addUser("john_doe");
        boolean exists = assertDoesNotThrow(() -> {
            return userService.userExists("john_doe");
        }, "Checking if a user exists should not throw an exception");
        assertEquals(true, exists);
    }
}

In this example, the UserServiceTest class tests the UserService methods using assertDoesNotThrow. It includes tests for adding, removing, and checking the existence of users to ensure that these operations do not throw any exceptions.

Conclusion

The assertDoesNotThrow method in JUnit is used for verifying that a given block of code does not throw any exception. By using assertDoesNotThrow and its various overloads, you can ensure that your tests provide clear feedback when exceptions are unexpectedly thrown. Understanding and using the assertDoesNotThrow method effectively is crucial for developing robust and maintainable Java applications.

Leave a Comment

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

Scroll to Top