1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
| import org.junit.jupiter.api.*; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.condition.*; import org.junit.jupiter.params.*; import org.junit.jupiter.params.provider.*;
import java.util.stream.Stream;
public class JUnit5ExampleTest {
@BeforeAll static void beforeAll() { System.out.println("Before All Tests"); }
@AfterAll static void afterAll() { System.out.println("After All Tests"); }
@BeforeEach void beforeEach() { System.out.println("Before Each Test"); }
@AfterEach void afterEach() { System.out.println("After Each Test"); }
@Test void simpleTest() { int sum = 2 + 3; assertEquals(5, sum, "Sum should be 5"); }
@Test void failedTest() { int product = 3 * 3; assertNotEquals(10, product, "Product should not be 10"); }
@Test void exceptionTest() { Exception exception = assertThrows(ArithmeticException.class, () -> { int result = 10 / 0; }); assertEquals("/ by zero", exception.getMessage()); }
@Test @EnabledOnOs(OS.LINUX) void testOnLinux() { System.out.println("Running test on Linux OS"); }
@Test @EnabledOnOs(OS.WINDOWS) void testOnWindows() { System.out.println("Running test on Windows OS"); }
@ParameterizedTest @ValueSource(ints = {1, 2, 3}) void parameterizedTestWithValueSource(int number) { assertTrue(number > 0, "Number should be greater than 0"); }
@ParameterizedTest @MethodSource("provideNumbersForMultiplication") void parameterizedTestWithMethodSource(int number1, int number2, int expectedResult) { assertEquals(expectedResult, number1 * number2); }
private static Stream<Arguments> provideNumbersForMultiplication() { return Stream.of( Arguments.of(2, 3, 6), Arguments.of(3, 5, 15), Arguments.of(4, 6, 24) ); }
@TestFactory Stream<DynamicTest> dynamicTests() { return Stream.of( DynamicTest.dynamicTest("Test 1", () -> assertEquals(1, 1)), DynamicTest.dynamicTest("Test 2", () -> assertEquals(2, 2)) ); }
@Test @Tag("fastFail") void fastFailTest() { assertTrue(false, "This test should fail and stop immediately"); }
@Test @Tag("unit") void unitTest() { assertTrue(true, "This is a unit test"); }
@Test @Tag("integration") void integrationTest() { assertTrue(true, "This is an integration test"); }
@Test @EnabledIfSystemProperty(named = "os.name", matches = ".*Windows.*") void testOnlyForWindows() { System.out.println("This test will run only on Windows"); } }
|