|
| 1 | +package com.baeldung.junit5.timeout; |
| 2 | + |
| 3 | +import org.junit.jupiter.api.Nested; |
| 4 | +import org.junit.jupiter.api.Test; |
| 5 | +import org.junit.jupiter.api.Timeout; |
| 6 | +import org.junit.jupiter.params.ParameterizedTest; |
| 7 | +import org.junit.jupiter.params.provider.ValueSource; |
| 8 | + |
| 9 | +import java.util.concurrent.TimeUnit; |
| 10 | + |
| 11 | + |
| 12 | +@Timeout(5) |
| 13 | +class TimeoutUnitTest { |
| 14 | + |
| 15 | + @Test |
| 16 | + @Timeout(1) |
| 17 | + void shouldFailAfterOneSecond() { |
| 18 | + slowMethod(); |
| 19 | + } |
| 20 | + |
| 21 | + @Test |
| 22 | + @Timeout(value = 5, unit = TimeUnit.MINUTES, threadMode = Timeout.ThreadMode.SEPARATE_THREAD) |
| 23 | + void shouldUseADifferentThread() { |
| 24 | + System.out.println(Thread.currentThread().getName()); |
| 25 | + slowMethod(); |
| 26 | + } |
| 27 | + |
| 28 | + @Test |
| 29 | + void shouldFailAfterDefaultTimeoutOfFiveSeconds() { |
| 30 | + slowMethod(); |
| 31 | + } |
| 32 | + |
| 33 | + @Test |
| 34 | + @Timeout(value = 2, unit = TimeUnit.MINUTES) |
| 35 | + void shouldFailAfterTwoMinutes() { |
| 36 | + slowMethod(); |
| 37 | + } |
| 38 | + |
| 39 | + @Timeout(1) |
| 40 | + @ParameterizedTest |
| 41 | + @ValueSource(ints = {1, 2, 3, 4, 5}) |
| 42 | + void eachTestShouldFailAfterOneSecond(int input) { |
| 43 | + slowMethod(); |
| 44 | + } |
| 45 | + |
| 46 | + @Nested |
| 47 | + class NestedClassWithoutTimeout { |
| 48 | + @Test |
| 49 | + void shouldFailAfterParentsDefaultTimeoutOfFiveSeconds() { |
| 50 | + slowMethod(); |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + @Nested |
| 55 | + @Timeout(3) |
| 56 | + class NestedClassWithTimeout { |
| 57 | + |
| 58 | + @Test |
| 59 | + void shouldFailAfterNestedClassTimeoutOfThreeSeconds() { |
| 60 | + slowMethod(); |
| 61 | + } |
| 62 | + |
| 63 | + @Test |
| 64 | + @Timeout(1) |
| 65 | + void shouldFailAfterOneSecond() { |
| 66 | + slowMethod(); |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + private void slowMethod() { |
| 71 | + try { |
| 72 | +// Thread.sleep(10_000); |
| 73 | +// just for demonstration purposes |
| 74 | +// tests cannot fail on the pipeline, bue we need failing examples in the article |
| 75 | + } catch (Exception e) { |
| 76 | + throw new RuntimeException(e); |
| 77 | + } |
| 78 | + } |
| 79 | +} |
0 commit comments