기존에 사용하던 Junit, AssertJ, Mockito의 기능과 비슷하되, 코틀린 DSL을 활용하여 테스트를 진행할 수 있게 해주는 Test Framework
다양한 Test Style을 통하여 Kotest를 작성할 수 있다.
Kotest에서 테스트는 TestContext -> Unit가 되는 function이다. (아래 참고)
class MyFirstTestClass : FunSpec({
test("my first test") {
1 + 2 shouldBe 3
}
})
모든 Assertion들은 test style 내부 블록에서 선언하면 된다.
코틀린에는 다양한 테스트 스타일이 존재한다.
그중 상황에 맞거나 가독성이 제일 좋다고 생각하는 스타일을 택하면 될 것 같다.
Kotest는 각 test case마다 Test instance를 어떻게 생성(관리)할지 선택할 수 있으며, IsolationMode enum으로 선택 가능하다. 옵션은 다음과 같다.
SingleInstance (default)InstancePerLeafInstancePerTest이름에서 파악 가능하듯이, 모든 test case를 하나의 instance로 실행하게 된다.
→ 따라서 stateful한 테스트가 진행된다.
이 역시 이름에서 파악 가능하듯이, inner context를 포함한, 매 test case마다 새로운 test instance가 생성된다.
→ 따라서 stateless한 테스트가 진행된다.
inner context를 제외한, 매 leaf test case마다 테스트 인스턴스가 생성된다.
매 테스트 전후로 실행하고자 하는 어떠한 행동을 정의함.
ex : setup, clean 등
class TestSpec : WordSpec({
beforeTest {
println("Starting a test $it")
}
afterTest { (test, result) ->
println("Finished spec with result $result")
}
"this test" should {
"be alive" {
println("Johnny5 is alive!")
}
}
})
위와 같이, beforeTest와 afterTest를 호출하면, Kotest에서 자동으로 TestListener를 생성/등록해주어
정의한 beforeTest와 afterTest를 실행시킨다.
val startTest: BeforeTest = {
println("Starting a test $it")
}
class TestSpec : WordSpec({
// used once
beforeTest(startTest)
"this test" should {
"be alive" {
println("Johnny5 is alive!")
}
}
})
class OtherSpec : WordSpec({
// used twice
beforeTest(startTest)
"this test" should {
"fail" {
fail("boom")
}
}
})
위와 같이 BeforeTest를 별도의 변수(startTest)로 정의하여 재사용성을 높일 수 있다.