|
| 1 | +package io.sentry.kotlin |
| 2 | + |
| 3 | +import io.sentry.IScopes |
| 4 | +import kotlinx.coroutines.GlobalScope |
| 5 | +import kotlinx.coroutines.async |
| 6 | +import kotlinx.coroutines.launch |
| 7 | +import kotlinx.coroutines.test.runTest |
| 8 | +import org.mockito.kotlin.check |
| 9 | +import org.mockito.kotlin.mock |
| 10 | +import org.mockito.kotlin.verify |
| 11 | +import kotlin.test.Test |
| 12 | +import kotlin.test.assertSame |
| 13 | +import kotlin.test.assertTrue |
| 14 | + |
| 15 | +class SentryCoroutineExceptionHandlerTest { |
| 16 | + |
| 17 | + class Fixture { |
| 18 | + val scopes = mock<IScopes>() |
| 19 | + |
| 20 | + fun getSut(): SentryCoroutineExceptionHandler { |
| 21 | + return SentryCoroutineExceptionHandler(scopes) |
| 22 | + } |
| 23 | + } |
| 24 | + |
| 25 | + @Test |
| 26 | + fun `captures unhandled exception in launch coroutine`() = runTest { |
| 27 | + val fixture = Fixture() |
| 28 | + val handler = fixture.getSut() |
| 29 | + val exception = RuntimeException("test") |
| 30 | + |
| 31 | + GlobalScope.launch(handler) { |
| 32 | + throw exception |
| 33 | + }.join() |
| 34 | + |
| 35 | + verify(fixture.scopes).captureEvent( |
| 36 | + check { |
| 37 | + assertSame(exception, it.throwable) |
| 38 | + } |
| 39 | + ) |
| 40 | + } |
| 41 | + |
| 42 | + @Test |
| 43 | + fun `captures unhandled exception in launch coroutine with child`() = runTest { |
| 44 | + val fixture = Fixture() |
| 45 | + val handler = fixture.getSut() |
| 46 | + val exception = RuntimeException("test") |
| 47 | + |
| 48 | + GlobalScope.launch(handler) { |
| 49 | + launch { |
| 50 | + throw exception |
| 51 | + }.join() |
| 52 | + }.join() |
| 53 | + |
| 54 | + verify(fixture.scopes).captureEvent( |
| 55 | + check { |
| 56 | + assertSame(exception, it.throwable) |
| 57 | + } |
| 58 | + ) |
| 59 | + } |
| 60 | + |
| 61 | + @Test |
| 62 | + fun `captures unhandled exception in async coroutine`() = runTest { |
| 63 | + val fixture = Fixture() |
| 64 | + val handler = fixture.getSut() |
| 65 | + val exception = RuntimeException("test") |
| 66 | + |
| 67 | + val deferred = GlobalScope.async() { |
| 68 | + throw exception |
| 69 | + } |
| 70 | + GlobalScope.launch(handler) { |
| 71 | + deferred.await() |
| 72 | + }.join() |
| 73 | + |
| 74 | + verify(fixture.scopes).captureEvent( |
| 75 | + check { |
| 76 | + assertTrue { exception.toString().equals(it.throwable.toString()) } // stack trace will differ |
| 77 | + } |
| 78 | + ) |
| 79 | + } |
| 80 | +} |
0 commit comments