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:

Java Program to Construct a Random Graph by the Method of Random Edge Selection
Java – Convert File to InputStream
Lớp Collections trong Java (Collections Utility Class)
Removing all duplicates from a List in Java
A Guide To UDP In Java
Java Program to Implement Sorted Vector
Bootstrapping Hibernate 5 with Spring
Java Program to Implement D-ary-Heap
Apache Tiles Integration with Spring MVC
Tránh lỗi ConcurrentModificationException trong Java như thế nào?
Java Program to Check Whether a Given Point is in a Given Polygon
Java InputStream to String
Lớp TreeMap trong Java
Request a Delivery / Read Receipt in Javamail
Spring Boot - Bootstrapping
Java Program to Find the Longest Subsequence Common to All Sequences in a Set of Sequences
Java Program to Find Nearest Neighbor Using Linear Search
Automatic Property Expansion with Spring Boot
Java Map With Case-Insensitive Keys
Spring MVC and the @ModelAttribute Annotation
Easy Ways to Write a Java InputStream to an OutputStream
Java Program to Implement Miller Rabin Primality Test Algorithm
Tính kế thừa (Inheritance) trong java
Java Program to do a Depth First Search/Traversal on a graph non-recursively
Java Program to Find Whether a Path Exists Between 2 Given Nodes
Java Program to Find Median of Elements where Elements are Stored in 2 Different Arrays
Spring Boot - Application Properties
Getting the Size of an Iterable in Java
Spring Boot Tutorial – Bootstrap a Simple Application
Spring RestTemplate Request/Response Logging
Java Web Services – Jersey JAX-RS – REST và sử dụng REST API testing tools với Postman
Java Program to Implement Borwein Algorithm