JUnit Assertions

Introduction

In this chapter, we will explore JUnit assertions. Assertions are methods used in tests to check if the actual output of the code matches the expected output. JUnit provides a variety of assertion methods to validate test outcomes. Understanding and using these assertions effectively is crucial for writing robust and reliable tests.

What are Assertions?

Assertions are statements in test methods that validate whether a certain condition is true or false. They are used to check if the expected outcome of a test is met. If the condition specified in an assertion fails, the test fails. Assertions help ensure that the code behaves as expected and can catch bugs early in the development process.

Common Assertions in JUnit

JUnit offers several assertion methods to validate different conditions. Here are some of the most commonly used assertions:

  • assertEquals(expected, actual, message)
  • assertNotEquals(expected, actual, message)
  • assertTrue(condition, message)
  • assertFalse(condition, message)
  • assertNull(object, message)
  • assertNotNull(object, message)
  • assertThrows(expectedType, executable, message)

1. assertEquals

The assertEquals method checks if two values are equal. If they are not, the test fails, and the provided message is displayed.

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

public class CalculatorTest {

    @Test
    public void testAdd() {
        Calculator calculator = new Calculator();
        int result = calculator.add(2, 3);
        assertEquals(5, result, "2 + 3 should equal 5");
    }
}

Explanation: This test checks if the add method of the Calculator class returns the correct sum. If the result is not 5, the test fails with the message “2 + 3 should equal 5”.

2. assertNotEquals

The assertNotEquals method checks if two values are not equal. If they are equal, the test fails and the provided message is displayed.

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

public class CalculatorTest {

    @Test
    public void testAddNotEquals() {
        Calculator calculator = new Calculator();
        int result = calculator.add(2, 3);
        assertNotEquals(6, result, "2 + 3 should not equal 6");
    }
}

Explanation: This test checks if the add method does not return 6 when adding 2 and 3. If the result is 6, the test fails with the message “2 + 3 should not equal 6”.

3. assertTrue

The assertTrue method checks if a condition is true. If it is false, the test fails and the provided message is displayed.

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

public class StringUtilsTest {

    @Test
    public void testIsPalindrome() {
        StringUtils stringUtils = new StringUtils();
        boolean result = stringUtils.isPalindrome("racecar");
        assertTrue(result, "'racecar' should be a palindrome");
    }
}

Explanation: This test checks if the isPalindrome method correctly identifies “racecar” as a palindrome. If isPalindrome returns false, the test fails with the message “‘racecar’ should be a palindrome”.

4. assertFalse

The assertFalse method checks if a condition is false. If it is true, the test fails, and the provided message is displayed.

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

public class StringUtilsTest {

    @Test
    public void testIsNotPalindrome() {
        StringUtils stringUtils = new StringUtils();
        boolean result = stringUtils.isPalindrome("hello");
        assertFalse(result, "'hello' should not be a palindrome");
    }
}

Explanation: This test checks if the isPalindrome method correctly identifies “hello” as not being a palindrome. If isPalindrome returns true, the test fails with the message “‘hello’ should not be a palindrome”.

5. assertNull

The assertNull method checks if an object is null. If it is not null, the test fails, and the provided message is displayed.

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

public class ObjectTest {

    @Test
    public void testObjectIsNull() {
        Object obj = null;
        assertNull(obj, "Object should be null");
    }
}

Explanation: This test checks if the object obj is null. If obj is not null, the test fails with the message “Object should be null”.

6. assertNotNull

The assertNotNull method checks if an object is not null. If it is null, the test fails, and the provided message is displayed.

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

public class ObjectTest {

    @Test
    public void testObjectIsNotNull() {
        Object obj = new Object();
        assertNotNull(obj, "Object should not be null");
    }
}

Explanation: This test checks if the object obj is not null. If obj is null, the test fails with the message “Object should not be null”.

7. assertThrows

The assertThrows method checks if a piece of code throws a specific exception. If the expected exception is not thrown, the test fails, and the provided message is displayed.

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

public class ExceptionTest {

    @Test
    public void testException() {
        Exception exception = assertThrows(NumberFormatException.class, () -> {
            Integer.parseInt("invalid");
        }, "Expected NumberFormatException to be thrown");
        assertEquals("For input string: \"invalid\"", exception.getMessage());
    }
}

Explanation: This test checks if parsing an invalid string as an integer throws a NumberFormatException. If no exception is thrown, or a different exception is thrown, the test fails with the message “Expected NumberFormatException to be thrown”. It also checks if the exception message matches the expected message.

Demonstrating Assertions in a Complete Example

Let’s combine several assertions in a comprehensive example to test a Calculator class and a StringUtils class.

Calculator Complete Example

Calculator Class

public class Calculator {
    public int add(int a, int b) {
        return a + b;
    }

    public int subtract(int a, int b) {
        return a - b;
    }
}

CalculatorTest Class

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

public class CalculatorTest {

    private Calculator calculator = new Calculator();

    @Test
    public void testAdd() {
        int result = calculator.add(2, 3);
        assertEquals(5, result, "2 + 3 should equal 5");
    }

    @Test
    public void testAddNotEquals() {
        int result = calculator.add(2, 3);
        assertNotEquals(6, result, "2 + 3 should not equal 6");
    }

    @Test
    public void testSubtract() {
        int result = calculator.subtract(5, 3);
        assertEquals(2, result, "5 - 3 should equal 2");
    }

    @Test
    public void testSubtractNotEquals() {
        int result = calculator.subtract(5, 3);
        assertNotEquals(3, result, "5 - 3 should not equal 3");
    }
}

Explanation: These tests check the add and subtract methods of the Calculator class using assertEquals and assertNotEquals to ensure the results are as expected.

StringUtils Complete Example

StringUtils Class

public class StringUtils {

    public String reverse(String input) {
        return new StringBuilder(input).reverse().toString();
    }

    public boolean isPalindrome(String input) {
        String reversed = reverse(input);
        return input.equals(reversed);
    }
}

StringUtilsTest Class

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

public class StringUtilsTest {

    private StringUtils stringUtils = new StringUtils();

    @Test
    public void testIsPalindrome() {
        boolean result = stringUtils.isPalindrome("racecar");
        assertTrue(result, "'racecar' should be a palindrome");
    }

    @Test
    public void testIsNotPalindrome() {
        boolean result = stringUtils.isPalindrome("hello");
        assertFalse(result, "'hello' should not be a palindrome");
    }

    @Test
    public void testReverse() {
        String result = stringUtils.reverse("hello");
        assertEquals("olleh", result, "The reverse of 'hello' should be 'olleh'");
    }
}

Explanation: These tests check the isPalindrome and reverse methods of the StringUtils class using assertTrue, assertFalse, and assertEquals to ensure the methods work as expected.

Conclusion

JUnit assertions are crucial for validating test outcomes. They help ensure that your code behaves as expected by checking various conditions, such as equality, nullity, and exception throwing. By mastering these assertions, you can write more robust and reliable tests for your Java applications.

Leave a Comment

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

Scroll to Top