Kotlin Multiplatform test interceptors with Burst

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:

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!

Get Burst on GitHub.