반응형

dependencies

dependencies {
    ...
    // JUnit 5 = JUnit Platform + JUnit Jupiter + JUnit Vintage
    testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.2'
    testImplementation 'org.junit.jupiter:junit-jupiter-params:5.8.2'
    testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.2'

    compileOnly 'org.projectlombok:lombok:1.18.22'
    annotationProcessor 'org.projectlombok:lombok:1.18.22'
    testCompileOnly 'org.projectlombok:lombok:1.18.22'
    testAnnotationProcessor 'org.projectlombok:lombok:1.18.22'
}

StandardDemo

public class StandardDemo {
    @BeforeAll
    public static void beforeAll() {
        System.out.println("beforeAll");
    }

    @AfterAll
    public static void afterAll() {
        System.out.println("afterAll");
    }

    @BeforeEach
    public void beforeEach() {
        System.out.println("beforeEach");
    }

    @AfterEach
    public void afterEach() {
        System.out.println("afterEach");
    }

    @Test
    public void basicTest() {
        System.out.println("basicTest");
        assertTrue(true);
    }

    @Test
    @Disabled("for test")
    public void ignoreTest() {
        System.out.println("ignoreTest");
        assertTrue(false);
    }
}

DisplayNameDemo

@DisplayName("display name demo")
public class DisplayNameDemo {
    @Test
    @DisplayName("display name test1")
    public void test1() {
    }

    @Nested
    @DisplayNameGeneration(DisplayNameGenerator.ReplaceUnderscores.class)
    public class A_year_is_not_supported {
        @Test
        public void if_it_is_zero() { // if it is zero
        }

        @DisplayName("A negative value for year is not supported by the leap year computation.")
        @ParameterizedTest(name = "For example, year {0} is not supported.")
        @ValueSource(ints = {-1, -4})
        public void if_it_is_negative(int year) { // For example, year {year} is not supported.
        }
    }

    @Nested
    @IndicativeSentencesGeneration(separator = " -> ", generator = DisplayNameGenerator.ReplaceUnderscores.class)
    public class A_year_is_a_leap_year {
        @Test
        public void if_it_is_divisible_by_4_but_not_by_100() { // -> if it is divisible by 4 but not by 100
        }

        @ParameterizedTest(name = "Year {0} is a leap year.")
        @ValueSource(ints = {2016, 2020, 2048})
        public void if_it_is_one_of_the_following_years(int year) { // Year {year} is a leap year.
        }
    }
}

AssertionsDemo

public class AssertionsDemo {
    @Test
    public void standardAssertions() {
        assertEquals(2, 1 + 1);
        assertEquals(4, 2 + 2, "The optional failure message is now the last parameter");
        assertTrue('a' < 'b', () -> "Assertion messages can be lazily evaluated -- to apublic void constructing complex messages unnecessarily.");
    }

    @Test
    public void groupedAssertions() {
        assertAll("person",
            () -> assertEquals("Jane", "Jane"),
            () -> assertEquals("Doe", "Doe")
        );
    }

    @Test
    public void dependentAssertions() {
        assertAll("properties",
            () -> {
                String firstName = "Jane";
                assertNotNull(firstName);

                assertAll("first name",
                    () -> assertTrue(firstName.startsWith("J")),
                    () -> assertTrue(firstName.endsWith("e"))
                );
            },
            () -> {
                String lastName = "Doe";
                assertNotNull(lastName);

                assertAll("last name",
                    () -> assertTrue(lastName.startsWith("D")),
                    () -> assertTrue(lastName.endsWith("e"))
                );
            }
        );
    }

    @Test
    public void exceptionTesting() {
        Exception exception = assertThrows(IndexOutOfBoundsException.class, () -> new ArrayList<>().get(100));
        assertEquals("Index 100 out of bounds for length 0", exception.getMessage());
    }

    @Test
    public void timeoutNotExceeded() {
        assertTimeout(ofSeconds(2), () -> { // 2초 넘어가면 테스트 실패
            // Thread.sleep(5000);
            assertTrue(true);
        });
    }

    @Test
    public void timeoutNotExceededWithResult() {
        String actualResult = assertTimeout(ofSeconds(2), () -> {
            // Thread.sleep(5000);
            return "a result";
        });
        assertEquals("a result", actualResult);
    }

    @Test
    public void timeoutExceededWithPreemptiveTermination() {
        // The following assertion fails with an error message similar to:
        // execution timed out after 10 ms
        assertTimeoutPreemptively(ofMillis(10), () -> {
            // Simulate task that takes more than 10 ms.
            new CountDownLatch(1).await();
        });
    }
}

ConditionsDemo

public class ConditionsDemo {
    @Test
    @EnabledOnOs({OS.WINDOWS, OS.MAC})
    public void onWindowsOrMac() {
        System.out.println("onWindowsOrMac");
    }

    @Test
    @DisabledOnOs({OS.WINDOWS, OS.MAC})
    public void notOnWindowsAndMac() {
        System.out.println("notOnWindowsAndMac");
    }

    @Test
    @EnabledOnJre({JRE.JAVA_8, JRE.JAVA_11})
    public void onJava8OrJava11() {
        System.out.println("onJava8OrJava11");
    }

    @Test
    @DisabledOnJre({JRE.JAVA_8, JRE.JAVA_11})
    public void notOnJava8AndJava11() {
        System.out.println("notOnJava8AndJava11");
    }

    @Test
    @EnabledForJreRange(min = JRE.JAVA_8, max = JRE.JAVA_11)
    public void onFromJava8To11() {
        System.out.println("onFromJava8To11");
    }

    @Test
    @DisabledForJreRange(min = JRE.JAVA_8, max = JRE.JAVA_11)
    public void notOnFromJava8To11() {
        System.out.println("notOnFromJava8To11");
    }

    @Test
    @EnabledIfSystemProperty(named = "java.version", matches = "11.*")
    public void onJava11Matched() {
        System.out.println("onJava11Matched : " + System.getProperty("java.version"));
    }

    @Test
    @DisabledIfSystemProperty(named = "java.version", matches = "11.*")
    public void notOnJava11Matched() {
        System.out.println("notOnJava11Matched : " + System.getProperty("java.version"));
    }

    @Test
    @EnabledIf("demo04.ExternalCondition#customCondition") // {packagePath}.{className}#{methodName}
    public void customCondition() {
        System.out.println("customCondition");
    }
}
public class ExternalCondition {
    public static boolean customCondition() {
        return true;
    }
}

OrderedTestsDemo

@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class OrderedTestsDemo {
    @Test
    @Order(3)
    public void test3() {
        System.out.println("test3");
    }

    @Test
    @Order(2)
    public void test2() {
        System.out.println("test2");
    }

    @Test
    @Order(1)
    public void test1() {
        System.out.println("test1");
    }
}

OrderedNestedTestClassesDemo

@TestClassOrder(ClassOrderer.OrderAnnotation.class)
public class OrderedNestedTestClassesDemo {
    @Nested
    @Order(2)
    public class SecondaryTests {
        @Test
        public void test2() {
            System.out.println("test2");
        }
    }

    @Nested
    @Order(1)
    public class PrimaryTests {
        @Test
        public void test1() {
            System.out.println("test1");
        }
    }
}

NestedDemo

@DisplayName("A stack")
public class NestedDemo {
    private Stack<Object> stack;

    @Test
    @DisplayName("is instantiated with new Stack()")
    public void isInstantiatedWithNew() {
        new Stack<>();
    }

    @Nested
    @DisplayName("when new")
    public class WhenNew {
        @BeforeEach
        public void createNewStack() {
            stack = new Stack<>();
        }

        @Test
        @DisplayName("is empty")
        public void isEmpty() {
            assertTrue(stack.isEmpty());
        }

        @Test
        @DisplayName("throws EmptyStackException when popped")
        public void throwsExceptionWhenPopped() {
            assertThrows(EmptyStackException.class, stack::pop);
        }

        @Test
        @DisplayName("throws EmptyStackException when peeked")
        public void throwsExceptionWhenPeeked() {
            assertThrows(EmptyStackException.class, stack::peek);
        }

        @Nested
        @DisplayName("after pushing an element")
        public class AfterPushing {
            private String anElement = "an element";

            @BeforeEach
            public void pushAnElement() {
                stack.push(anElement);
            }

            @Test
            @DisplayName("it is no longer empty")
            public void isNotEmpty() {
                assertFalse(stack.isEmpty());
            }

            @Test
            @DisplayName("returns the element when popped and is empty")
            public void returnElementWhenPopped() {
                assertEquals(anElement, stack.pop());
                assertTrue(stack.isEmpty());
            }

            @Test
            @DisplayName("returns the element when peeked but remains not empty")
            public void returnElementWhenPeeked() {
                assertEquals(anElement, stack.peek());
                assertFalse(stack.isEmpty());
            }
        }
    }
}

TestInfoDemo

@DisplayName("TestInfo Demo")
public class TestInfoDemo {
    public TestInfoDemo(TestInfo testInfo) {
        assertEquals("TestInfo Demo", testInfo.getDisplayName());
    }

    @BeforeEach
    public void init(TestInfo testInfo) {
        String displayName = testInfo.getDisplayName();
        assertTrue(displayName.equals("TEST 1") || displayName.equals("test2()"));
    }

    @Test
    @DisplayName("TEST 1")
    @Tag("my-tag")
    public void test1(TestInfo testInfo) {
        assertEquals("TEST 1", testInfo.getDisplayName());
        assertTrue(testInfo.getTags().contains("my-tag"));
    }

    @Test
    public void test2() {
    }
}

CustomExtensionDemo

@ExtendWith(RandomValueExtension.class)
public class CustomExtensionDemo {
    @Test
    public void injectsInteger(@RandomValue int i, @RandomValue int j) {
        System.out.println(i);
        System.out.println(j);
    }

    @Test
    public void injectsDouble(@RandomValue double d) {
        System.out.println(d);
    }
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface RandomValue {
}
public class RandomValueExtension implements ParameterResolver {
    @Override
    public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) {
        return parameterContext.isAnnotated(RandomValue.class);
    }

    @Override
    public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) {
        Class<?> type = parameterContext.getParameter().getType();
        Random random = extensionContext.getRoot().getStore(ExtensionContext.Namespace.GLOBAL).getOrComputeIfAbsent(Random.class);
        if (int.class.equals(type)) {
            return random.nextInt();
        }
        if (double.class.equals(type)) {
            return random.nextDouble();
        }
        throw new ParameterResolutionException("No random generator implemented for " + type);
    }
}

TestInterfaceDemo

public class TestInterfaceDemo implements TestLifecycleLogger, TestInterfaceDynamicTestsDemo {
    @Test
    public void isEqualValue() {
        assertEquals(1, "a".length(), "is always equal");
    }
}
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
public interface TestLifecycleLogger {
    @BeforeAll
    default void beforeAllTests() {
        System.out.println("Before all tests");
    }

    @AfterAll
    default void afterAllTests() {
        System.out.println("After all tests");
    }

    @BeforeEach
    default void beforeEachTest(TestInfo testInfo) {
        System.out.println("About to execute " + testInfo.getDisplayName());
    }

    @AfterEach
    default void afterEachTest(TestInfo testInfo) {
        System.out.println("Finished executing " + testInfo.getDisplayName());
    }
}
public interface TestInterfaceDynamicTestsDemo {
    @TestFactory
    default Stream<DynamicTest> dynamicTestsForPalindromes() {
        return Stream.of("racecar", "radar").map(text -> dynamicTest(text, () -> assertTrue(text.startsWith("r"))));
    }
}

TestInterfaceDemoV2

public class TestInterfaceDemoV2 implements ComparableContract<String>, EqualsContract<String> {
    @Override
    public String createValue() {
        return "banana";
    }

    @Override
    public String createSmallerValue() {
        return "apple"; // 'a' < 'b' in "banana"
    }

    @Override
    public String createNotEqualValue() {
        return "cherry";
    }
}
public interface Testable<T> {
    T createValue();
}
public interface EqualsContract<T> extends Testable<T> {
    T createNotEqualValue();

    @Test
    default void valueEqualsItself() {
        T value = createValue();
        assertEquals(value, value);
    }

    @Test
    default void valueDoesNotEqualNull() {
        T value = createValue();
        assertFalse(value.equals(null));
    }

    @Test
    default void valueDoesNotEqualDifferentValue() {
        T value = createValue();
        T differentValue = createNotEqualValue();
        assertNotEquals(value, differentValue);
        assertNotEquals(differentValue, value);
    }
}
public interface ComparableContract<T extends Comparable<T>> extends Testable<T> {
    T createSmallerValue();

    @Test
    default void returnsZeroWhenComparedToItself() {
        T value = createValue();
        assertEquals(0, value.compareTo(value));
    }

    @Test
    default void returnsPositiveNumberWhenComparedToSmallerValue() {
        T value = createValue();
        T smallerValue = createSmallerValue();
        assertTrue(value.compareTo(smallerValue) > 0);
    }

    @Test
    default void returnsNegativeNumberWhenComparedToLargerValue() {
        T value = createValue();
        T smallerValue = createSmallerValue();
        assertTrue(smallerValue.compareTo(value) < 0);
    }
}

RepeatedTestsDemo

public class RepeatedTestsDemo {
    @RepeatedTest(3)
    public void testRepeat1(TestInfo testInfo, RepetitionInfo repetitionInfo) {
        String expected = String.format("repetition %d of %d", repetitionInfo.getCurrentRepetition(), repetitionInfo.getTotalRepetitions());
        String actual = testInfo.getDisplayName();
        assertEquals(expected, actual);
        assertEquals("testRepeat1", testInfo.getTestMethod().get().getName());
    }

    @RepeatedTest(value = 3, name = "{displayName} : {currentRepetition} / {totalRepetitions}")
    @DisplayName("repeat2")
    public void testRepeat2(TestInfo testInfo, RepetitionInfo repetitionInfo) {
        String expected = String.format("repeat2 : %d / %d", repetitionInfo.getCurrentRepetition(), repetitionInfo.getTotalRepetitions());
        String actual = testInfo.getDisplayName();
        assertEquals(expected, actual);
        assertEquals("testRepeat2", testInfo.getTestMethod().get().getName());
    }

    @RepeatedTest(value = 3, name = RepeatedTest.LONG_DISPLAY_NAME)
    @DisplayName("repeat3")
    public void testRepeat3(TestInfo testInfo, RepetitionInfo repetitionInfo) {
        String expected = String.format("repeat3 :: repetition %d of %d", repetitionInfo.getCurrentRepetition(), repetitionInfo.getTotalRepetitions());
        String actual = testInfo.getDisplayName();
        assertEquals(expected, actual);
        assertEquals("testRepeat3", testInfo.getTestMethod().get().getName());
    }
}

ParameterizedValueSourceDemo

public class ParameterizedValueSourceDemo {
    @ParameterizedTest
    @ValueSource(strings = {"racecar", "radar", "race"})
    public void testStrings(String candidate) {
        assertTrue(candidate.startsWith("r"));
    }

    @ParameterizedTest
    @ValueSource(ints = {1, 2, 3})
    public void testInts(int candidate) {
        assertTrue(candidate > 0);
    }
}

ParameterizedEnumSourceDemo

public class ParameterizedEnumSourceDemo {
    @ParameterizedTest
    @EnumSource(names = {"DAYS", "HOURS"})
    public void testEnum(ChronoUnit unit) {
        assertTrue(Set.of(ChronoUnit.DAYS, ChronoUnit.HOURS).contains(unit));
    }

    @ParameterizedTest
    @EnumSource(mode = EXCLUDE, names = {"ERAS", "FOREVER"})
    void testEnumExclude(ChronoUnit unit) {
        assertFalse(Set.of(ChronoUnit.ERAS, ChronoUnit.FOREVER).contains(unit));
    }

    @ParameterizedTest
    @EnumSource(mode = MATCH_ALL, names = "^.*DAYS$")
    public void testEnumMatch(ChronoUnit unit) {
        assertTrue(unit.name().endsWith("DAYS"));
    }
}

ParameterizedMethodSourceDemo

public class ParameterizedMethodSourceDemo {
    @ParameterizedTest
    @MethodSource("demo14.ExternalTestMethodSource#args")
    public void testMethodSource2(String argument) {
        assertTrue(argument.startsWith("a"));
    }

    @ParameterizedTest
    @MethodSource("forTestMethodSource")
    public void testMethodSource(String argument) {
        assertTrue(argument.startsWith("a"));
    }

    @ParameterizedTest
    @MethodSource("forTestMultiArgsMethodSource")
    public void testMultiArgsMethodSource(String str, int num, List<String> list) {
        assertEquals(5, str.length());
        assertTrue(num >= 1 && num <= 2);
        assertEquals(2, list.size());
    }

    private static Stream<String> forTestMethodSource() {
        return Stream.of("apple", "alpha");
    }

    private static Stream<Arguments> forTestMultiArgsMethodSource() {
        return Stream.of(
            arguments("apple", 1, Arrays.asList("a", "b")),
            arguments("lemon", 2, Arrays.asList("x", "y"))
        );
    }
}
public class ExternalTestMethodSource {
    public static Stream<String> args() {
        return Stream.of("apple", "alpha");
    }
}

ParameterizedCsvSourceDemo

public class ParameterizedCsvSourceDemo {
    @ParameterizedTest
    @CsvSource({
        "apple,         1",
        "banana,        2",
        "'lemon, lime', 0xF1",
        "strawberry,    700_000"
    })
    public void testCsvSource(String fruit, int rank) {
        assertNotNull(fruit);
        assertNotEquals(0, rank);
    }

    @ParameterizedTest
    @CsvSource(
        delimiter = '|',
        value = {
            "apple | 1",
            "banana | 2",
            "'lemon, lime' | 0xF1",
            "strawberry | 700_000"
        })
    public void testCsvSource2(String fruit, int rank) {
        assertNotNull(fruit);
        assertNotEquals(0, rank);
    }

    @ParameterizedTest
    @CsvSource({
        "1, Jane, 1990-05-20",
        "2, John, 1989-10-22"
    })
    public void testWithArgumentsAccessor(ArgumentsAccessor accessor) {
        Person person = new Person(
            accessor.getInteger(0),
            accessor.getString(1),
            accessor.get(2, LocalDate.class)
        );

        switch (person.getId()) {
            case 1:
                assertEquals(new Person(1, "Jane", LocalDate.of(1990, 5, 20)), person);
                break;
            case 2:
                assertEquals(new Person(2, "John", LocalDate.of(1989, 10, 22)), person);
                break;
        }
    }

    @ParameterizedTest
    @CsvSource({
        "1, Jane, 1990-05-20",
        "2, John, 1989-10-22"
    })
    public void testWithArgumentsAggregator(@AggregateWith(PersonAggregator.class) Person person) {
        switch (person.getId()) {
            case 1:
                assertEquals(new Person(1, "Jane", LocalDate.of(1990, 5, 20)), person);
                break;
            case 2:
                assertEquals(new Person(2, "John", LocalDate.of(1989, 10, 22)), person);
                break;
        }
    }
}
@RequiredArgsConstructor
@Data
public class Person {
    private final Integer id;
    private final String name;
    private final LocalDate birth;
}
public class PersonAggregator implements ArgumentsAggregator {
    @Override
    public Person aggregateArguments(ArgumentsAccessor accessor, ParameterContext context) throws ArgumentsAggregationException {
        return new Person(
            accessor.getInteger(0),
            accessor.getString(1),
            accessor.get(2, LocalDate.class)
        );
    }
}

ParameterizedArgumentsSourceDemo

public class ParameterizedArgumentsSourceDemo {
    @ParameterizedTest
    @ArgumentsSource(TestArgumentsSource.class)
    public void testArgumentsSource(String argument) {
        assertTrue(argument.startsWith("a"));
    }
}
public class TestArgumentsSource implements ArgumentsProvider {
    @Override
    public Stream<? extends Arguments> provideArguments(ExtensionContext context) {
        return Stream.of("apple", "alpha").map(Arguments::of);
    }
}

ParameterizedConvertingDemo

public class ParameterizedConvertingDemo {
    @ParameterizedTest
    @ValueSource(strings = {"1", "2", "3"})
    public void testStringToIntegerConverter(Integer argument) {
        System.out.println(argument);
    }

    @ParameterizedTest
    @EnumSource(ChronoUnit.class)
    public void testEnumToStringConverter(@ConvertWith(EnumToStringConverter.class) String argument) {
        assertNotNull(ChronoUnit.valueOf(argument));
    }

    @ParameterizedTest
    @EnumSource(ChronoUnit.class)
    public void testEnumToStringConverterV2(@ConvertWith(EnumToStringConverterV2.class) String argument) {
        assertNotNull(ChronoUnit.valueOf(argument));
    }

    @ParameterizedTest
    @ValueSource(strings = {"01.01.2017", "31.12.2017"})
    public void testWithExplicitJavaTimeConverter(@JavaTimeConversionPattern("dd.MM.yyyy") LocalDate argument) {
        assertEquals(2017, argument.getYear());
    }
}
public class EnumToStringConverter extends SimpleArgumentConverter {
    @Override
    protected Object convert(Object source, Class<?> targetType) {
        return source instanceof Enum<?>
            ? ((Enum<?>) source).name()
            : String.valueOf(source);
    }
}
public class EnumToStringConverterV2 extends TypedArgumentConverter<Enum, String> {
    protected EnumToStringConverterV2() {
        super(Enum.class, String.class);
    }

    @Override
    protected String convert(Enum source) throws ArgumentConversionException {
        return source.name();
    }
}

ParameterizedDisplayNameDemo

public class ParameterizedDisplayNameDemo {
    @DisplayName("CustomDisplay")
    @ParameterizedTest(name = "[{displayName}] [{index}] [{arguments}] [{0}, {1}]")
    @CsvSource({
        "1, apple",
        "2, banana",
        "3, 'lemon, lime'"
    })
    public void testCustomDisplayName(int id, String fruit) {
    }
}

DynamicTestsDemo

public class DynamicTestsDemo {
    @TestFactory
    public Collection<DynamicTest> dynamicTestsFromCollection() {
        return Arrays.asList(
            dynamicTest("1st dynamic test", () -> assertTrue(true)),
            dynamicTest("2nd dynamic test", () -> assertTrue(true))
        );
    }

    @TestFactory
    public Iterable<DynamicTest> dynamicTestsFromIterable() {
        return Arrays.asList(
            dynamicTest("3rd dynamic test", () -> assertTrue(true)),
            dynamicTest("4th dynamic test", () -> assertTrue(true))
        );
    }

    @TestFactory
    public Iterator<DynamicTest> dynamicTestsFromIterator() {
        return Arrays.asList(
            dynamicTest("5th dynamic test", () -> assertTrue(true)),
            dynamicTest("6th dynamic test", () -> assertTrue(true))
        ).iterator();
    }

    @TestFactory
    public DynamicTest[] dynamicTestsFromArray() {
        return new DynamicTest[]{
            dynamicTest("7th dynamic test", () -> assertTrue(true)),
            dynamicTest("8th dynamic test", () -> assertTrue(true))
        };
    }

    @TestFactory
    public Stream<DynamicTest> dynamicTestsFromStream() {
        return Stream.of("racecar", "radar", "mom", "dad")
            .map(text -> dynamicTest(text, () -> assertTrue(true)));
    }

    @TestFactory
    public Stream<DynamicTest> dynamicTestsFromIntStream() {
        return IntStream.iterate(0, n -> n + 2).limit(10)
            .mapToObj(n -> dynamicTest("test" + n, () -> assertTrue(n % 2 == 0)));
    }

    @TestFactory
    public Stream<DynamicTest> dynamicTestsFromStreamFactoryMethodWithNames() {
        Stream<Named<String>> inputStream = Stream.of(
            named("racecar is a palindrome", "racecar"),
            named("radar is also a palindrome", "radar"),
            named("mom also seems to be a palindrome", "mom"),
            named("dad is yet another palindrome", "dad")
        );

        return DynamicTest.stream(inputStream, text -> assertTrue(true));
    }

    @TestFactory
    public Stream<DynamicNode> dynamicTestsWithContainers() {
        return Stream.of("A", "B", "C")
            .map(input -> dynamicContainer("Container " + input, Stream.of(
                dynamicTest("not null", () -> assertNotNull(input)),
                dynamicContainer("properties", Stream.of(
                    dynamicTest("length > 0", () -> assertTrue(input.length() > 0)),
                    dynamicTest("not empty", () -> assertFalse(input.isEmpty()))
                ))
            )));
    }

    @TestFactory
    public DynamicNode dynamicNodeSingleTest() {
        return dynamicTest("'pop' is a palindrome", () -> assertTrue(true));
    }

    @TestFactory
    public DynamicNode dynamicNodeSingleContainer() {
        return dynamicContainer("palindromes",
            Stream.of("racecar", "radar", "mom", "dad").map(text -> dynamicTest(text, () -> assertTrue(text.length() >= 3)))
        );
    }
}

TempDirectoryDemo

public class TempDirectoryDemo {
    @TempDir
    public static Path sharedTempDir;

    @Test
    public void writeItemsToFile() throws IOException {
        Path file = sharedTempDir.resolve("test.txt");

        Files.write(file, Arrays.asList("a", "b", "c"), StandardOpenOption.CREATE_NEW);

        assertEquals(Arrays.asList("a", "b", "c"), Files.readAllLines(file));
    }

    @Test
    public void copyFileFromSourceToTarget(@TempDir Path source, @TempDir Path target) throws IOException {
        Path sourceFile = source.resolve("test.txt");
        Files.write(sourceFile, Arrays.asList("a", "b", "c"), StandardOpenOption.CREATE_NEW);

        Path targetFile = Files.copy(sourceFile, target.resolve("test.txt"));

        assertNotEquals(sourceFile, targetFile);
        assertEquals(Arrays.asList("a", "b", "c"), Files.readAllLines(sourceFile));
        assertEquals(Arrays.asList("a", "b", "c"), Files.readAllLines(targetFile));
    }
}

TimeoutDemo

public class TimeoutDemo {
    @BeforeEach
    @Timeout(5)
    public void setUp() throws InterruptedException {
        // fails if execution time exceeds 5 seconds
        // Thread.sleep(6000);
    }

    @Test
    @Timeout(value = 100, unit = TimeUnit.MILLISECONDS)
    public void failsIfExecutionTimeExceeds100Milliseconds() throws InterruptedException {
        // fails if execution time exceeds 100 milliseconds
        // Thread.sleep(150);
    }
}

참고

반응형

'Development > Java' 카테고리의 다른 글

[Java] Base64  (0) 2022.04.26
[Java] Singleton Pattern  (0) 2022.01.07
[Java] JUnit4  (0) 2021.11.23
[Java] Hash Algorithm  (0) 2021.11.17
[Java] Stream  (0) 2021.09.09

+ Recent posts