JUnit annotations are a type of syntactic meta-data that can be added to Java source code to improve the readability and structure of the code. JUnit 5 annotates test methods with various annotations. Let's go over the most common JUnit 5 annotations now.
@Test: This annotation indicates that the method is a test method. It should be noted that this annotation does not accept any attributes.
@ParameterizedTest: Parameterized tests allow you to run the same test multiple times with different arguments.
@RepeatedTest: By using this annotation and specifying the total number of repetitions, JUnit 5 allows you to repeat a test an unlimited number of times.
@DisplayName: Custom display names can be declared by test classes and test methods and will be displayed by test runners and test reports.
@BeforeEach: This annotation specifies that the annotated method should run before each test method.
@AfterEach: This annotation indicates that the annotated method should be run following each test method.
@BeforeAll: This annotation calls a method before all tests are run.
@AfterAll: This annotation causes the annotated method to be executed only after all tests have been completed.
@Tag: This annotation can be used to declare tags that will be used to filter tests at the class or method level.
@Disabled: This annotation is used at the class or method level to disable or skip tests.
Let’s look at a few annotation examples:
package io.educative.junit5;import org.junit.jupiter.api.*;import static org.junit.jupiter.api.Assertions.*;public class DemoTest {// @Test annotation@Testvoid emptyTest() {}// @DisplayName annotation@Test@DisplayName("A demo test")public void DisplayNameTest() {}// @RepeatedTest annotation@RepeatedTest(3)@DisplayName("simple")void simpleTest() {}// @Disabled annotation@Disabled@Test@DisplayName("disabled test")void disabledTest() {assertTrue(2>1);}}
Lines 7 and 12: We denote the @Test
and @DisplayName
annotations.
Line 16: We add a repetition of three which means that the method repeats three times.
Line 21: We add the @Disabled
annotation that disables the method.
Free Resources