Given is the example from kotlin-test github docs, but i don't see beforeEach or beforeClass concept here. I want to understand,
class MyTests : StringSpec({
"length should return size of string" {
"hello".length shouldBe 5
}
"startsWith should test for a prefix" {
"world" should startWith("wor")
}
})
Very similar to your own answer @JTeam, but use the init {} constructor block to declare your tests and then you can override methods directly in the class.
class MyTest : StringSpec() {
override fun beforeTest(description: Description) {
super.beforeTest(description)
println("Before every spec/test case")
}
override fun beforeSpec(description: Description, spec: Spec) {
super.beforeSpec(description, this)
println("Before every test suite")
}
override fun afterTest(description: Description, result: TestResult) {
super.afterTest(description, result)
println("After every spec/test case")
}
override fun afterSpec(description: Description, spec: Spec) {
super.afterSpec(description, spec)
println("After every test suite")
}
init {
"test should run " {
"Hello".shouldHaveLength(4)
}
"test2 should run " {
"Hello World".shouldHaveLength(10)
}
}
}
In newer versions of Kotest
(I think that starting from 4.0.0) there are lifecylce functions on TestCofiguration
and there's no need for the init block anymore:
import io.kotest.core.spec.style.StringSpec
import io.kotest.matchers.string.shouldHaveLength
class MyTest : StringSpec({
beforeTest {
println("Before every spec/test case")
}
beforeSpec {
println("Before every test suite")
}
afterTest {
println("After every spec/test case")
}
afterSpec {
println("After every test suite")
}
"test 1 " {
println("run test 1")
"Hello" shouldHaveLength 4
}
"test 2 " {
println("run test 2")
"Hello World" shouldHaveLength 10
}
})
More info
After doing some research in the github docs and kotlin-test framework source code, below is the code to write beforeTest, beforeSpec, afterTest, afterSpec
class MyTest : StringSpec({
"test should run " {
"Hello".shouldHaveLength(4)
}
"test2 should run " {
"Hello World".shouldHaveLength(10)
}
}) {
override fun beforeTest(description: Description) {
super.beforeTest(description)
println("Before every spec/test case")
}
override fun beforeSpec(description: Description, spec: Spec) {
super.beforeSpec(description, this)
println("Before every test suite")
}
override fun afterTest(description: Description, result: TestResult) {
super.afterTest(description, result)
println("After every spec/test case")
}
override fun afterSpec(description: Description, spec: Spec) {
super.afterSpec(description, spec)
println("After every test suite")
}
}
This is not looking elegant, if there is any way which can make it elegant, please post it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With