JUnit Jupiter Annotations: Chapter 1

Overview

In order to run JUnit tests, you need to tell the JUnit Platform about your test classes: which methods are test methods, which methods are part of the test method lifecycle, whether to use extensions, and so on.

You do this through annotations, which are metadata about how to run your tests.

You can download the code from GitHub if you like:

https://github.com/makotogo/HelloJUnit5

In this post, I’ll cover the two annotations you’re likely to use with JUnit, along with examples of each.

@Test

@Test
@DisplayName("When numbers are > 0")
public void testAdd() {
  // Unit test code here
}

Use this annotation to tell the JUnit platform that the method is a test method. This means it will be invoked at the appropriate point in the lifecycle, complete with all the bells and whistles.

Every method you want to run as a test method needs to be annotated with the @Test annotation.

@DisplayName

@DisplayName("Testing using JUnit 5")
public class JUnit5AppTest {
.
.
  @Test   
  @DisplayName("When numbers are > 0")   
  public void testAdd() {     
    // Unit test code here 
  }
.
.
}

By default, the name displayed for a test class or method is the name of the class or method, respectively. The @DisplayName annotation tells JUnit to use the specified name instead.

Check it out: compare the following examples, first without the annotation, then with it. (Both are from the JUnit View in Eclipse)

Without the @DisplayName annotation:

 WithoutDisplayName

And with the @DisplayName annotation:

WithDisplayName

In this simple example, you can see already that the report is cleaner. But when there are several test methods, the value of @DisplayName gets even clearer:

DisplayNameLargerTest

Video

In the video below, I’ll go over the annotations in detail, and you can watch me explain the code as I write it.

Conclusion

In this article, I showed you two of the annotations from the JUnit Jupiter API you’ll definitely want to use. Stay tuned for more in this series, where I’ll show you more annotations from the JUnit Jupiter API.

Be sure to follow along with this series here on my blog, and the accompanying videos on my YouTube channel.

To learn more about the annotations provided by the JUnit Jupiter API visit the JUnit 5 User’s Guide.

Check out my IBM developerWorks JUnit 5 Tutorial Series:

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s