Unit testing is the foundation of reliable software development. Before exploring advanced mocking frameworks like Mockito, it’s crucial to understand how to write basic unit tests with JUnit 5.
1. Create a Simple Business Class
Let’s create a simple class called SomeBusinessImpl
that contains a method to calculate the sum of integers in an array.
Directory Structure
src ├── main │ └── java │ └── com.learnitweb.unittesting.business │ └── SomeBusinessImpl.java └── test └── java └── com.learnitweb.unittesting.business └── SomeBusinessImplTest.java
SomeBusinessImpl.java
package com.in28minutes.unittesting.business; public class SomeBusinessImpl { public int calculateSum(int[] data) { int sum = 0; for (int value : data) { sum += value; } return sum; } }
Explanation:
- The method
calculateSum
takes anint[]
as input. - It iterates through the array and computes the total sum.
- The method returns the final result.
2. Writing Unit Tests with JUnit 5
Now, let’s write a unit test class to test calculateSum
with different scenarios.
SomeBusinessImplTest.java
package com.learnitweb.unittesting.business; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; public class SomeBusinessImplTest { @Test void calculateSum_basicScenario() { SomeBusinessImpl business = new SomeBusinessImpl(); int result = business.calculateSum(new int[] {1, 2, 3}); int expectedResult = 6; assertEquals(expectedResult, result); } @Test void calculateSum_emptyArray() { SomeBusinessImpl business = new SomeBusinessImpl(); int result = business.calculateSum(new int[] {}); int expectedResult = 0; assertEquals(expectedResult, result); } @Test void calculateSum_oneValue() { SomeBusinessImpl business = new SomeBusinessImpl(); int result = business.calculateSum(new int[] {5}); int expectedResult = 5; assertEquals(expectedResult, result); } }
Explanation of Key Concepts
- The @Test annotation tells JUnit that the method is a test method.
assertEquals(expected, actual)
checks if the actual value matches the expected value.- If they don’t match, JUnit throws an
AssertionError
, and the test fails. - If the actual output doesn’t match the expected result, the test fails and shows a clear error:
org.opentest4j.AssertionFailedError: Expected :8 Actual :6
This helps you identify bugs early.