JUnit – Assertions
In this JUnit tutorial, we will provide a detailed explanation about assertions in JUnit, their types, usage, and best practices.
What are Assertions in JUnit?
Assertions are tools in JUnit that help check if your code is working correctly. They are used in tests to compare what your code produces (actual output) with what you expect it to produce (expected result). If the two don’t match, the test will fail and show a message explaining what went wrong. This helps you quickly find and fix problems in your code.
JUnit provides a wide range of assertions to validate different types of conditions, including equality, truthiness, nullity, exceptions, and timeouts.
Commonly Used Assertions in JUnit
Here’s a list of commonly used assertions in JUnit along with their purposes:
assertEquals
: Checks if two values are equal.assertNotEquals
: Verifies that two values are not equal.assertTrue
: Validates that a condition is true.assertFalse
: Validates that a condition is false.assertNull
: Ensures that an object is null.assertNotNull
: Ensures that an object is not null.assertArrayEquals
: Checks if two arrays are equal.assertThrows
: Validates that a specific exception is thrown.assertTimeout
: Ensures that a task completes within a specified time.
Each assertion method provides an optional failure message, which is displayed if the assertion fails. This message is useful for debugging.
Detailed Examples of Assertions
Let’s look at each assertion in detail with examples:
1 assertEquals
The assertEquals
method checks if two values are equal. It compares primitive types, objects, and strings.
src/test/java/AssertionTests.java
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
class AssertionTests {
@Test
void testAssertEquals() {
int expected = 10;
int actual = 5 + 5;
assertEquals(expected, actual, "The actual value does not match the expected value.");
}
}
Since the expected and actual values are equal, the test passes as shown in the following video.
If the actual value is not equal to the expected value, the test fails and displays the failure message.
2 assertNotEquals
The assertNotEquals
method verifies that two values are not equal.
src/test/java/AssertionTests.java
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
class AssertionTests {
@Test
void testAssertNotEquals() {
String str1 = "JUnit";
String str2 = "Testing";
assertNotEquals(str1, str2, "The strings should not be equal.");
}
}
This ensures that the test passes only when the two values are different.
Since the values in the given example are not equal, the assertion assertNotEquals()
passes and the test passes, as shown in the following video.
3 assertTrue and assertFalse
These methods validate that a condition is either true or false.
src/test/java/AssertionTests.java
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
class AssertionTests {
@Test
void testAssertTrueAndFalse() {
assertTrue(10 > 5, "10 is greater than 5");
assertFalse(5 > 10, "5 is not greater than 10");
}
}
These assertions are commonly used for conditional checks in test cases.
10 > 5
is true, and therefore assertTrue()
method passes.
5 > 10
is false, and therefore assertFalse()
method passes, because the give condition is false and we need to assert if it is false.
We have run the Test in Eclipse, and the test results are shown in the following video.
4 assertNull and assertNotNull
These methods check whether an object is null or not null.
src/test/java/AssertionTests.java
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
class AssertionTests {
@Test
void testAssertNullAndNotNull() {
String str1 = null;
assertNull(str1, "The object should be null.");
String str2 = "JUnit";
assertNotNull(str2, "The object should not be null.");
}
}
These assertions are useful for testing object initialization and null checks.
assertNull()
method passes as the give object str1
is null.
assertNotNull()
method passes as the give object str2
is not null.
5 assertArrayEquals
This method checks if two arrays are equal in length and content.
src/test/java/AssertionTests.java
@Test
void testAssertArrayEquals() {
int[] expected = {1, 2, 3};
int[] actual = {1, 2, 3};
assertArrayEquals(expected, actual, "The arrays are not equal.");
}
Since the two arrays are equal in length and values, the assertion method assertArrayEquals()
passes and the whole test passes.
The test would have failed if the arrays differ in length or any of their elements.
6 assertThrows
The assertThrows
method validates that a specific exception is thrown by the tested code.
src/test/java/AssertionTests.java
@Test
void testAssertThrows() {
assertThrows(ArithmeticException.class, () -> {
int result = 1 / 0;
}, "Division by zero should throw an ArithmeticException.");
}
This assertion is essential for testing error handling and edge cases.
7 assertTimeout
The assertTimeout
method ensures that a task completes within a specified duration.
src/test/java/AssertionTests.java
import java.time.Duration;
@Test
void testAssertTimeout() {
assertTimeout(Duration.ofSeconds(1), () -> {
Thread.sleep(500); // Simulates a task
}, "The task should complete within 1 second.");
}
This is useful for performance testing and ensuring efficient code execution.
Best Practices for Using Assertions
- Use Descriptive Messages: Provide meaningful messages to make debugging easier.
- Test One Condition Per Assertion: Keep tests focused and simple by testing one condition at a time.
- Use assertThrows for Exception Testing: Validate error scenarios explicitly.
- Prefer assertAll for Grouped Assertions: Combine multiple assertions into a single logical test case using
assertAll
. - Test Edge Cases: Include boundary and unusual inputs in your tests.
Conclusion
Assertions are the foundation of writing effective tests in JUnit. They allow developers to verify the correctness of their code and ensure that all functionality behaves as expected. By understanding and using different types of assertions, you can write robust and meaningful tests that improve code quality and prevent bugs in production.
In this guide, we covered the most commonly used assertions in JUnit, their usage, and practical examples. With these tools in your testing toolkit, you’re well-equipped to handle a wide variety of testing scenarios.