Explore Topics

Unit Testing with JUnit 5

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:

If you’re using Gradle, add this to your build.gradle:

Writing Tests with JUnit 5

Here’s a simple example of how to write a unit test using JUnit 5.

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:

For Gradle, run: