|
| 1 | +/* |
| 2 | + * Copyright 2016-2023 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. |
| 3 | + */ |
| 4 | +package kotlinx.coroutines.test |
| 5 | + |
| 6 | +import org.junit.Test |
| 7 | +import kotlin.test.* |
| 8 | + |
| 9 | +/** |
| 10 | + * Tests that check the behavior of the test framework when there are stray uncaught exceptions. |
| 11 | + * These tests are JVM-only because only the JVM allows to set a global uncaught exception handler and validate the |
| 12 | + * behavior without checking the test logs. |
| 13 | + * Nevertheless, each test here has a corresponding test in the common source set that can be run manually. |
| 14 | + */ |
| 15 | +class UncaughtExceptionsTest { |
| 16 | + |
| 17 | + val oldExceptionHandler = Thread.getDefaultUncaughtExceptionHandler() |
| 18 | + val uncaughtExceptions = mutableListOf<Throwable>() |
| 19 | + |
| 20 | + @BeforeTest |
| 21 | + fun setUp() { |
| 22 | + Thread.setDefaultUncaughtExceptionHandler { thread, throwable -> |
| 23 | + uncaughtExceptions.add(throwable) |
| 24 | + } |
| 25 | + } |
| 26 | + |
| 27 | + @AfterTest |
| 28 | + fun tearDown() { |
| 29 | + Thread.setDefaultUncaughtExceptionHandler(oldExceptionHandler) |
| 30 | + } |
| 31 | + |
| 32 | + @Test |
| 33 | + fun testReportingStrayUncaughtExceptionsBetweenTests() { |
| 34 | + TestScopeTest().testReportingStrayUncaughtExceptionsBetweenTests() |
| 35 | + assertEquals(1, uncaughtExceptions.size, "Expected 1 uncaught exception, but got $uncaughtExceptions") |
| 36 | + val exception = assertIs<TestException>(uncaughtExceptions.single()) |
| 37 | + assertEquals("x", exception.message) |
| 38 | + } |
| 39 | + |
| 40 | + @Test |
| 41 | + fun testExceptionCaptorCleanedUpOnPreliminaryExit() { |
| 42 | + RunTestTest().testExceptionCaptorCleanedUpOnPreliminaryExit() |
| 43 | + assertEquals(2, uncaughtExceptions.size, "Expected 2 uncaught exceptions, but got $uncaughtExceptions") |
| 44 | + for (exception in uncaughtExceptions) { |
| 45 | + assertIs<TestException>(exception) |
| 46 | + } |
| 47 | + assertEquals("A", uncaughtExceptions[0].message) |
| 48 | + assertEquals("B", uncaughtExceptions[1].message) |
| 49 | + } |
| 50 | +} |
0 commit comments