Kotlin Multiplatform test interceptors with Burst
Posted by
Jesse Wilson
on
Last year we announced Burst, our Kotlin Multiplatform library for parameterized tests.
I recently needed another JUnit feature that’s absent on Kotlin/Multiplatform: test rules! They offer a simple way to reuse behavior across tests. Here’s some of my favorites:
- Paparazzi is Cash App’s snapshot testing for Android. The library’s main entry point is a test rule.
- MockWebServer is an HTTP server focused on testing HTTP clients. A major contributor to OkHttp’s stability is its MockWebServer-powered test suite!
- JUnit’s Timeout rule lets me write difficult integration tests without the risk of hanging my test suite.
JUnit rules don’t work on non-JVM platforms, so with Burst 2.8 we’re introducing a Kotlin Multiplatform alternative called TestInterceptor
. It’s straightforward to create one:
class TemporaryDirectory : TestInterceptor {
lateinit var path: Path
private set
override fun intercept(testFunction: TestFunction) {
path = createTemporaryDirectory(testFunction)
try {
testFunction()
} finally {
deleteTemporaryDirectory(path)
}
}
}
Use @InterceptTest
to apply it:
class DocumentStorageTest {
@InterceptTest
val temporaryDirectory = TemporaryDirectory()
@Test
fun happyPath() {
DocumentWriter().write(SampleData.document, temporaryDirectory.path)
val decoded = DocumentReader().read(temporaryDirectory.path)
assertThat(decoded).isEqualTo(SampleData.document)
}
}
Burst can also intercept suspending tests with CoroutineTestInterceptor
. JUnit rules can’t do that!