JUnit 5 @Test Annotation

1. Overview

In this article, we’ll make a quick review of JUnit’s @Test annotation. This annotation provides a powerful tool for performing unit and regression testing.

2. Maven Configuration

To use the latest version of JUnit 5, we’ll need to add the following Maven dependency:

<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-engine</artifactId>
    <version>5.1.0</version>
    <scope>test</scope>
</dependency>

We use the test scope because we don’t want Maven to include this dependency in our final build.

Since the surefire plugin doesn’t still natively fully support JUnit 5, we’ll also need to add a provider, which tells Maven where to find our tests:

<plugin>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.19.1</version>
    <dependencies>
        <dependency>
            <groupId>org.junit.platform</groupId>
            <artifactId>junit-platform-surefire-provider</artifactId>
            <version>1.0.2</version>
        </dependency>
    </dependencies>
</plugin>

In our configuration, we’ll use surefire 2.19.1 because, at the time of writing, version 2.20.x is not compatible with the junit-platform-surefire-provider.

3. Method Under Test

First of all, let’s build a simple method that we’ll use in our test scenarios to showcase the @Test annotation’s capabilities:

public boolean isNumberEven(Integer number) {
    return number % 2 == 0;
}

This method should return true if the argument passed is an even number and false otherwise. Now, let’s check out if it works the way it’s supposed to.

4. Testing the Method

For our example, we want to specifically check two scenarios:

  • when given an even number, the method should return true
  • when given an odd number, the method should return false

This means that the implementation code will call our isNumberEven method with different parameters and check that the result is what we expect.

In order for the tests to be recognized as such, we’ll add the @Test annotation. We can have as many of these as we want in a class, but it’s a good practice to put together only the related ones. Notice also that a test must not be private, nor may it return a value —otherwise it’ll just be ignored.

Given these considerations, let’s write our test methods:

@Test
void givenEvenNumber_whenCheckingIsNumberEven_thenTrue() {
    boolean result = bean.isNumberEven(8);

    Assertions.assertTrue(result);
}

@Test
void givenOddNumber_whenCheckingIsNumberEven_thenFalse() {
    boolean result = bean.isNumberEven(3);

    Assertions.assertFalse(result);
}

If we now run a Maven build, the surefire plugin will go through all the annotated methods in the classes placed under src/test/java and execute them, causing the build to fail if any test failures occur.

If you come from JUnit 4, be aware that in this version the annotation doesn’t accept any parameters. To check for a timeout or an exception thrown we would use assertions instead:

@Test
void givenLowerThanTenNumber_whenCheckingIsNumberEven_thenResultUnderTenMillis() {
    Assertions.assertTimeout(Duration.ofMillis(10), () -> bean.isNumberEven(3));
}
	
@Test
void givenNull_whenCheckingIsNumberEven_thenNullPointerException() {
    Assertions.assertThrows(NullPointerException.class, () -> bean.isNumberEven(null));
}

5. Conclusion

In this quick tutorial, we showed how to implement and run a simple JUnit test with the @Test annotation.

More about the JUnit framework can be found in this post which provides a general introduction.

All the code used in the examples is available in the GitHub project.

Related posts:

Spring Security OAuth2 – Simple Token Revocation
Number Formatting in Java
Java Program to Implement Tarjan Algorithm
Reactive WebSockets with Spring 5
Allow user:password in URL
Introduction to Spring Cloud Netflix – Eureka
Sorting in Java
Hướng dẫn sử dụng luồng vào ra nhị phân trong Java
OAuth2 for a Spring REST API – Handle the Refresh Token in Angular
Java Web Services – Jersey JAX-RS – REST và sử dụng REST API testing tools với Postman
Java Program to Represent Graph Using 2D Arrays
Java Program to Search Number Using Divide and Conquer with the Aid of Fibonacci Numbers
A Guide to the ViewResolver in Spring MVC
Hướng dẫn sử dụng biểu thức chính quy (Regular Expression) trong Java
ThreadPoolTaskExecutor corePoolSize vs. maxPoolSize
Java Program to Implement Ford–Fulkerson Algorithm
Java Program to Implement Best-First Search
Java Program to Implement Flood Fill Algorithm
Generating Random Dates in Java
Java Program to Implement Stein GCD Algorithm
Java Program to Find Maximum Element in an Array using Binary Search
Setting Up Swagger 2 with a Spring REST API
Partition a List in Java
Tính trừu tượng (Abstraction) trong Java
Optional trong Java 8
Tránh lỗi ConcurrentModificationException trong Java như thế nào?
Spring Boot: Customize Whitelabel Error Page
Java Program to Implement Fibonacci Heap
Java Program to Implement Control Table
How to Kill a Java Thread
Java Program to Implement LinkedTransferQueue API
Java Program to Implement SimpeBindings API