Skip to content

Instantly share code, notes, and snippets.

@OliverO2
Created September 2, 2025 14:03
Show Gist options
  • Select an option

  • Save OliverO2/c76cc2d8c66876af8cde024b1671f345 to your computer and use it in GitHub Desktop.

Select an option

Save OliverO2/c76cc2d8c66876af8cde024b1671f345 to your computer and use it in GitHub Desktop.
Kotest: Getting a fresh context per test with and without IsolationMode.InstancePerTest
import io.kotest.core.spec.IsolationMode
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.shouldBe
class MyTestSuiteInstancePerTest : FunSpec() {
override fun isolationMode(): IsolationMode = IsolationMode.InstancePerTest
private class MyClass(var myProperty: Int = 1)
private val myObject = MyClass()
init {
test("one") {
myObject.myProperty shouldBe 1
myObject.myProperty += 10
myObject.myProperty shouldBe 11
}
test("two") {
myObject.myProperty shouldBe 1
myObject.myProperty += 20
myObject.myProperty shouldBe 21
}
}
}
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.shouldBe
class MyTestSuiteWithoutIsolation1 : FunSpec() {
private class MyClass(var myProperty: Int = 1)
private class MyContext(val myObject: MyClass = MyClass())
private fun myTest(name: String, action: suspend MyContext.() -> Unit) = test(name) {
MyContext().action()
}
init {
myTest("one") {
myObject.myProperty shouldBe 1
myObject.myProperty += 10
myObject.myProperty shouldBe 11
}
myTest("two") {
myObject.myProperty shouldBe 1
myObject.myProperty += 20
myObject.myProperty shouldBe 21
}
}
}
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.shouldBe
class MyTestSuiteWithoutIsolation2 : FunSpec() {
private class MyClass(var myProperty: Int = 1)
private class MyContext {
val myObject: MyClass = MyClass()
}
init {
test("one", MyContext()) {
myObject.myProperty shouldBe 1
myObject.myProperty += 10
myObject.myProperty shouldBe 11
}
test("two", MyContext()) {
myObject.myProperty shouldBe 1
myObject.myProperty += 20
myObject.myProperty shouldBe 21
}
}
}
fun <Context> FunSpec.test(name: String, context: Context, action: suspend Context.() -> Unit) = test(name) {
context.action()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment