- 引入Spek单元测试框架:
- 在
build.gradle.kts
文件中添加Spek依赖:
testImplementation("org.spekframework.spek2:spek-dsl-jvm:2.0.16")
testRuntimeOnly("org.spekframework.spek2:spek-runner-junit5:2.0.16")
- 如果使用
build.gradle
(Groovy),依赖添加如下:
testImplementation 'org.spekframework.spek2:spek-dsl-jvm:2.0.16'
testRuntimeOnly 'org.spekframework.spek2:spek-runner-junit5:2.0.16'
- 编写Spek测试示例:
- 假设我们有一个简单的Kotlin函数
add
在MathUtils.kt
文件中:
package com.example
fun add(a: Int, b: Int): Int {
return a + b
}
- 编写Spek测试类
MathUtilsSpekTest.kt
:
package com.example
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
import kotlin.test.assertEquals
object MathUtilsSpekTest : Spek({
describe("add function") {
it("should return the sum of two numbers") {
val result = add(2, 3)
assertEquals(5, result)
}
}
})