首页 > 解决方案 > How to write beforeEach and beforeClass in kotlintest

问题描述

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")
  }
})

标签: kotlinkotlintestkotest

解决方案


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)
    }
  }
}

推荐阅读