Introduction
JUnit 5 is a widely used testing framework for Java applications. It offers a range of annotations that help streamline writing and managing tests. Understanding these annotations is crucial for writing effective and maintainable tests. This cheat sheet provides a quick reference to the most commonly used JUnit 5 annotations.
JUnit 5 Annotations Cheat Sheet
Here's a handy cheat sheet of the most commonly used JUnit 5 annotations, ordered by their usage and popularity:
JUnit 5 Annotation and Description
JUnit 5 Annotation | Description |
---|---|
@Test |
Marks a method as a test method. |
@BeforeEach |
Specifies a method to run before each test. |
@AfterEach |
Specifies a method to run after each test. |
@BeforeAll |
Specifies a method to run once before all tests in the class. It must be static. |
@AfterAll |
Specifies a method to run once after all tests in the class. It must be static. |
@Disabled |
Disables a test class or test method. |
@ParameterizedTest |
Marks a method as a parameterized test. |
@ValueSource |
Provides a simple source of literal values for parameterized tests. |
@EnumSource |
Provides a source of enum values for parameterized tests. |
@MethodSource |
Provides a source of arguments from a static method for parameterized tests. |
@CsvSource |
Provides a source of comma-separated values (CSV) for parameterized tests. |
@CsvFileSource |
Provides a source of CSV files for parameterized tests. |
@ArgumentsSource |
Provides a source of custom arguments for parameterized tests. |
@RepeatedTest |
Marks a method to be repeated a specified number of times. |
@TestFactory |
Denotes a method as a test factory for dynamic tests. |
@TestTemplate |
Indicates a method is a test template for repeated invocations. |
@TestMethodOrder |
Configures the test method execution order for the annotated test class. |
@TestInstance |
Specifies the lifecycle of test instances. |
@DisplayName |
Sets a custom display name for a test class or test method. |
@DisplayNameGeneration |
Specifies a custom display name generator for test methods. |
@Nested |
Denotes a nested, non-static test class. |
@Tag |
Declares tags for filtering tests. |
@ExtendWith |
Registers custom extensions. |
@RegisterExtension |
Registers an extension field or method parameter programmatically. |
@TempDir |
Injects a temporary directory that is deleted after the test. |
@Timeout |
Fails a test if it exceeds the specified execution time. |
@Test
Description: Marks a method as a test method.
Example:
@Test
void testAddition() {
assertEquals(2, 1 + 1);
}
Explanation: The testAddition
method will be executed as a test case. The assertEquals
method checks if the addition operation is correct.
@BeforeEach
Description: Specifies a method to run before each test.
Example:
@BeforeEach
void setUp() {
// Code to set up test data
}
Explanation: The setUp
method will run before each test method in the class, typically used to initialize test data.
@AfterEach
Description: Specifies a method to run after each test.
Example:
@AfterEach
void tearDown() {
// Code to clean up after each test
}
Explanation: The tearDown
method will run after each test method, commonly used for cleaning up resources.
@BeforeAll
Description: Specifies a method to run once before all tests in the class. Must be static.
Example:
@BeforeAll
static void initAll() {
// Code to run before all tests
}
Explanation: The initAll
method will run once before any of the test methods in the class, used for global initialization.
@AfterAll
Description: Specifies a method to run once after all tests in the class. Must be static.
Example:
@AfterAll
static void tearDownAll() {
// Code to run after all tests
}
Explanation: The tearDownAll
method will run once after all the test methods have run, used for global cleanup.
@Disabled
Description: Disables a test class or test method.
Example:
@Disabled
@Test
void testNotReady() {
// This test will not run
}
Explanation: The testNotReady
method will be ignored by the test runner.
@ParameterizedTest
Description: Marks a method as a parameterized test.
Example:
@ParameterizedTest
@ValueSource(strings = {"Hello", "JUnit"})
void testWithParameters(String word) {
assertNotNull(word);
}
Explanation: The testWithParameters
method will be executed multiple times, once for each value provided by @ValueSource
.
@ValueSource
Description: Provides a simple source of literal values for parameterized tests.
Example:
@ParameterizedTest
@ValueSource(ints = {1, 2, 3})
void testWithIntValues(int number) {
assertTrue(number > 0);
}
Explanation: The testWithIntValues
method will run three times, once for each integer in the @ValueSource
.
@EnumSource
Description: Provides a source of enum values for parameterized tests.
Example:
enum Day { MONDAY, TUESDAY, WEDNESDAY }
@ParameterizedTest
@EnumSource(Day.class)
void testWithEnumValues(Day day) {
assertNotNull(day);
}
Explanation: The testWithEnumValues
method will be executed for each enum value in the Day
enum.
@MethodSource
Description: Provides a source of arguments from a static method for parameterized tests.
Example:
static Stream<String> stringProvider() {
return Stream.of("apple", "banana");
}
@ParameterizedTest
@MethodSource("stringProvider")
void testWithMethodSource(String fruit) {
assertNotNull(fruit);
}
Explanation: The testWithMethodSource
method will run for each string provided by the stringProvider
method.
@CsvSource
Description: Provides a source of comma-separated values (CSV) for parameterized tests.
Example:
@ParameterizedTest
@CsvSource({
"apple, 1",
"banana, 2"
})
void testWithCsvSource(String fruit, int rank) {
assertNotNull(fruit);
assertTrue(rank > 0);
}
Explanation: The testWithCsvSource
method will run twice, once for each set of CSV values.
@CsvFileSource
Description: Provides a source of CSV files for parameterized tests.
Example:
@ParameterizedTest
@CsvFileSource(resources = "/data.csv")
void testWithCsvFileSource(String fruit, int rank) {
assertNotNull(fruit);
assertTrue(rank > 0);
}
Explanation: The testWithCsvFileSource
method will run for each row in the data.csv
file.
@ArgumentsSource
Description: Provides a source of custom arguments for parameterized tests.
Example:
class CustomArgumentsProvider implements ArgumentsProvider {
@Override
public Stream<? extends Arguments> provideArguments(ExtensionContext context) {
return Stream.of(
Arguments.of("apple", 1),
Arguments.of("banana", 2)
);
}
}
@ParameterizedTest
@ArgumentsSource(CustomArgumentsProvider.class)
void testWithArgumentsSource(String fruit, int rank) {
assertNotNull(fruit);
assertTrue(rank > 0);
}
Explanation: The testWithArgumentsSource
method will run for each set of arguments provided by the CustomArgumentsProvider
.
@RepeatedTest
Description: Marks a method to be repeated a specified number of times.
Example:
@RepeatedTest(5)
void repeatedTest(RepetitionInfo repetitionInfo) {
assertTrue(repetitionInfo.getCurrentRepetition() <= 5);
}
Explanation: The repeatedTest
method will run five times.
@TestFactory
Description: Denotes a method as a test factory for dynamic tests.
Example:
@TestFactory
Stream<DynamicTest> dynamicTestsFromStream() {
return Stream.of("A", "B", "C")
.map(str -> DynamicTest.dynamicTest("test" + str,
() -> assertNotNull(str)));
}
Explanation: The dynamicTestsFromStream
method provides a stream of dynamic tests.
@TestTemplate
Description: Indicates a method is a test template for repeated invocations.
Example:
@TestTemplate
@ExtendWith(MyTestTemplateInvocationContextProvider.class)
void testTemplate() {
// Test code
}
Explanation: The testTemplate
method will be executed using the MyTestTemplateInvocationContextProvider
.
@TestMethodOrder
Description: Configures the test method execution order for the annotated test class.
Example:
@TestMethodOrder(OrderAnnotation.class)
class OrderedTests {
@Test @Order(1) void testOne() { /* ... */ }
@Test @Order(2) void testTwo() { /* ... */ }
}
Explanation: The OrderedTests
class will execute testOne
before testTwo
.
@TestInstance
Description: Specifies the lifecycle of test instances.
Example:
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class PerClassTestInstance {
@BeforeAll void setUp() { /* ... */ }
@Test void test() { /* ... */ }
}
Explanation: The PerClassTestInstance
class uses a single instance for all test methods, allowing non-static @BeforeAll
and @AfterAll
methods.
@DisplayName
Description: Sets a custom display name for a test class or test method.
Example:
@DisplayName("Test Class Example")
class DisplayNameExample {
@Test @DisplayName("Test Method Example")
void testMethod() { /* ... */ }
}
Explanation: The custom display names make the test results more readable.
@DisplayNameGeneration
Description: Specifies a custom display name generator for test methods.
Example:
@DisplayNameGeneration(DisplayNameGenerator.ReplaceUnderscores.class)
class DisplayNameGenerationExample {
@Test void test_method_with_underscores() { /* ... */ }
}
Explanation: The DisplayNameGenerationExample
class uses the ReplaceUnderscores
generator to format method names.
@Nested
Description: Denotes a nested, non-static test class.
Example:
class OuterTest {
@Nested
class InnerTest {
@Test void innerTestMethod() { /* ... */ }
}
}
Explanation: The InnerTest
class is a nested test class within OuterTest
.
@Tag
Description: Declares tags for filtering tests.
Example:
@Tag("fast")
@Test void fastTest() { /* ... */ }
@Tag("slow")
@Test void slowTest() { /* ... */ }
Explanation: The fastTest
and slowTest
methods are tagged for filtering during test execution.
@ExtendWith
Description: Registers custom extensions.
Example:
@ExtendWith(MyExtension.class)
class ExtendWithExample {
@Test void test() { /* ... */ }
}
Explanation: The ExtendWithExample
class uses MyExtension
to extend its functionality.
@RegisterExtension
Description: Registers an extension field or method parameter programmatically.
Example:
class RegisterExtensionExample {
@RegisterExtension
static MyExtension myExtension = new MyExtension();
@Test void test() { /* ... */ }
}
Explanation: The RegisterExtensionExample
class programmatically registers MyExtension
.
@TempDir
Description: Injects a temporary directory that is deleted after the test.
Example:
class TempDirExample {
@TempDir Path tempDir;
@Test void test() throws IOException {
Files.createFile(tempDir.resolve("test.txt"));
}
}
Explanation: The TempDirExample
class uses a temporary directory for file operations.
@Timeout
Description: Fails a test if it exceeds the specified execution time.
Example:
@Test
@Timeout(5)
void testWithTimeout() {
// Test code
}
Explanation: The testWithTimeout
method will fail if it takes longer than 5 seconds to execute.
Conclusion
JUnit 5 annotations are essential for writing clean, effective, and maintainable tests. This cheat sheet provides a quick reference to the most commonly used Java JUnit 5 annotations, helping you streamline your testing process and ensure the reliability of your code.
By leveraging these annotations, you can simplify the setup of your test environments, make your tests more readable, and focus on ensuring your code works as intended. Keep this guide handy to enhance your productivity and take full advantage of JUnit 5's capabilities. Happy testing!
Comments
Post a Comment
Leave Comment