Unit Testing is a fundamental part of software development. It helps ensure that each individual component of your program works as expected. In Java, JUnit 5 is a widely-used framework for writing and running tests. Here’s a quick guide to get you started.
JUnit 5 is the latest version of the JUnit testing framework. It provides a lot of powerful features for unit testing, including:
- JUnit Platform for running tests.
- JUnit Jupiter for writing tests and extensions.
- JUnit Vintage for running JUnit 3 and 4 tests.
Setting up JUnit 5
To get started with JUnit 5, you’ll need to add the dependencies to your project’s build file. If you’re using Maven, add the following to your pom.xml
:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-api</artifactId> <version>5.8.2</version> <scope>test</scope> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-engine</artifactId> <version>5.8.2</version> <scope>test</scope> </dependency> |
If you’re using Gradle, add this to your build.gradle
:
1 2 |
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.2' testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.2' |
Writing Tests with JUnit 5
Here’s a simple example of how to write a unit test using JUnit 5.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; class CalculatorTest { @Test void testAddition() { Calculator calculator = new Calculator(); assertEquals(5, calculator.add(2, 3)); } @Test void testSubtraction() { Calculator calculator = new Calculator(); assertEquals(1, calculator.subtract(3, 2)); } } |
In the example above:
- The
@Test
annotation marks a method as a test. - The
assertEquals()
method checks if the expected result matches the actual result.
JUnit 5 Annotations
@Test
: Marks a method as a test method.@BeforeEach
: Runs before each test method to set up necessary preconditions.@AfterEach
: Runs after each test method to clean up.@BeforeAll
: Runs once before all tests, useful for setup tasks that are expensive.@AfterAll
: Runs once after all tests, ideal for cleanup.
Running Tests
You can run JUnit tests using your IDE (like IntelliJ IDEA or Eclipse) or from the command line.
For Maven, run:
1 |
mvn test |
For Gradle, run:
1 |
gradle test |