Hi, I'be alighted on this pattern for sharing cod...
# kotest
r
Hi, I'be alighted on this pattern for sharing code between specs:
Copy code
import io.kotest.core.spec.style.StringSpec
import io.kotest.matchers.shouldBe

@Suppress("UNCHECKED_CAST")
abstract class AbstractSpec(
  body: AbstractSpec.() -> Unit,
) : StringSpec(body as StringSpec.() -> Unit) {
  fun shared() {  }
  val sharedProperty = "foo"
}

class ConcreteSpec : AbstractSpec({
  "some test" {
    shared()
    sharedProperty shouldBe "foo"
  }
})
That unchecked cast bothers me, and suggests to me that there is probably a better way... could someone point me at the docs I've missed?
l
s
You can use AbstractSpec as the type in the body lambda
r
I think you're maybe looking for https://kotest.io/docs/framework/test-factories.html
Possibly... in the past I've used them for reusing tests rather than reusing fixtures. But it probably comes to the same thing if I think hard enough.
You can use AbstractSpec as the type in the body lambda
I'm probably being thick but I don't understand what you mean. This doesn't compile:
Copy code
abstract class AbstractSpec(
  body: AbstractSpec.() -> Unit,
) : StringSpec(body) {
  fun shared() {  }
  val sharedProperty = "foo"
}

class ConcreteSpec : AbstractSpec({
  "some test" {
    shared()
    sharedProperty shouldBe "foo"
  }
})
s
What's the compile error
r
Argument type mismatch: actual type is 'Function1<AbstractSpec, Unit>', but 'Function1<StringSpec, Unit>' was expected.
s
Oh just wrap the constructor invocation to apply as a string spec
I can show you once home afk atm
r
Think I've got it:
Copy code
abstract class AbstractSpec(
  body: AbstractSpec.() -> Unit,
) : StringSpec() {
  fun shared() {  }
  val sharedProperty = "foo"

  init {
    body()
  }
}

class ConcreteSpec : AbstractSpec({
  "some test" {
    shared()
    sharedProperty shouldBe "foo"
  }
})
s
Cool
r
Thanks for the pointer
s
No problem
t
r
The tests are all in the same module, there's no need to introduce a new configuration and source set for them to share code.