Kotlin 测试
Kotlin 测试教程:覆盖 kotlin.test 断言 API、JUnit 5 平台配置、@BeforeTest/@AfterTest 生命周期、@ParameterizedTest、runTest 与 gradlew test 过滤。
学完这一章,你能够
- Kotlin 测试教程:覆盖 kotlin.test 断言 API、JUnit 5 平台配置、@BeforeTest/@AfterTest 生命周期、@ParameterizedTest、runTest 与 gradlew test 过滤。
kotlin.test 与 JUnit 5 协作、断言与第一个单元测试
自动化单元测试用于在演进代码时快速验证回归。Kotlin 生态中,`JUnit 5` 担任 JVM 测试运行框架,负责发现 `@Test` 方法、调度生命周期与输出报告;`kotlin.test` 则是官方跨平台测试库,提供统一注解与断言 API(在 JVM 上通过适配器委托给 JUnit 5,在 JS/Native 上切换对应适配器),实现跨平台测试复用。新项目应直接选用 JUnit 5,并在 Gradle 中显式声明 `testImplementation(kotlin("test"))` 与 `tasks.test { useJUnitPlatform() }`。
测试源码放在 `src/test/kotlin` 且包名与主源码一致,测试类通常命名为 `<目标类>Test`,方法名应清晰表达被测行为。`kotlin.test` 内置 `assertEquals`(支持自定义失败消息重载)、`assertNotEquals`、`assertTrue`/`assertFalse`、`assertNull`/`assertNotNull`、`assertSame`/`assertNotSame`、`assertFailsWith<E> { ... }` 与 `assertContains`,断言失败时抛出 `AssertionError` 并在报告中精准展示期望值与实际值差异。
测试生命周期钩子与 JUnit 5 参数化测试
当多个用例需要隔离状态或共享初始化/清理逻辑时,可使用生命周期注解:`@BeforeTest` 与 `@AfterTest` 在 JVM 上映射为 JUnit 5 的 `@BeforeEach` 与 `@AfterEach`,于每个测试方法前后各执行一次,适合重建被测对象与临时数据(应避免放入耗时昂贵操作);类级一次性的 `@BeforeAll` 与 `@AfterAll` 在 Kotlin 中需定义于 `companion object` 内并加 `@JvmStatic` 供 JUnit 5 反射调用。
若同一段业务规则需要用多组边界输入反复校验,`kotlin.test` 本身不含参数化注解,在 JVM 项目可直接引入 JUnit 5 的 `@ParameterizedTest` 搭配 `@CsvSource`、`@ValueSource` 等数据源,将测试数据以表格形式声明,框架自动为每行生成独立报告条目。
协程虚拟时间测试 runTest、Gradle 过滤执行与常见问题
测试 `suspend` 函数与并发协程时,应引入 `kotlinx-coroutines-test` 并用 `runTest { ... }` 包裹测试体。`runTest` 创建绑定虚拟时钟的 `TestScope` 与 `TestDispatcher`,会自动快进跳过 `delay` 等待、支持通过 `testScheduler.advanceTimeBy(...)` 精确验证超时与重试节拍,并在结束前等待子协程完成以防止静默泄漏。
日常通过 `./gradlew test` 运行全部测试并在 `build/reports/tests/test/index.html` 查看 HTML 报告,借助 `--tests` 参数按类或方法精准过滤,CI 中常附加 `--no-daemon`。常见问题:勿混用 `kotlin.test.Test` 与 `org.junit.jupiter.api.Test`;漏写 `useJUnitPlatform()` 会导致 JUnit 5 用例完全不被发现;杜绝用例间共享可变状态依赖执行顺序;用 `runTest` 与替身对象隔离慢速 IO 提升反馈速度。
Kotlin 测试技术栈核心组件
| 组件 | 职责 | 典型内容 |
| JUnit 5 | JVM 测试执行框架,负责用例发现、生命周期与报告 | @Test 执行引擎、useJUnitPlatform()、扩展与参数化 |
| kotlin.test | 跨平台统一断言与基础测试注解库 | assertEquals、assertTrue、assertFailsWith、@BeforeTest |
| kotlinx-coroutines-test | 挂起函数与协程并发的确定性测试支持 | runTest、TestScope、虚拟时钟 TestDispatcher |
kotlin.test 常用断言函数速查
| 断言函数 | 用途 | 示例 |
| assertEquals | 断言期望值与实际值结构相等(==) | assertEquals(4, calculator.add(2, 2)) |
| assertNotEquals | 断言两值结构不相等 | assertNotEquals(5, calculator.add(2, 2)) |
| assertTrue | 断言布尔条件为 true | assertTrue(list.isEmpty()) |
| assertFalse | 断言布尔条件为 false | assertFalse(list.isNotEmpty()) |
| assertNull | 断言表达式结果为 null | assertNull(map["missing"]) |
| assertNotNull | 断言表达式结果非 null | assertNotNull(result) |
| assertSame | 断言两引用指向同一对象实例(===) | assertSame(a, b) |
| assertNotSame | 断言两引用指向不同对象实例(!==) | assertNotSame(a, b) |
| assertFailsWith | 断言代码块抛出指定类型异常并返回该异常对象 | assertFailsWith<IllegalArgumentException> { ... } |
| assertContains | 断言集合、区间或字符串包含目标元素 | assertContains(listOf(1, 2, 3), 2) |
测试生命周期注解与执行时机
| 注解 | 执行时机 | 典型用途 |
| @BeforeTest | 每个测试方法执行之前各触发一次 | 初始化新被测实例、准备隔离测试数据 |
| @AfterTest | 每个测试方法执行之后各触发一次 | 关闭句柄、清理临时文件与状态 |
| @BeforeAll | 整个测试类所有方法执行前仅运行一次(需 @JvmStatic) | 启动本地测试容器或加载重型只读夹具 |
| @AfterAll | 整个测试类所有方法执行后仅运行一次(需 @JvmStatic) | 停止测试服务并释放全局共享资源 |
Gradle 运行与过滤测试常用命令
| 命令 | 作用 |
| ./gradlew test | 编译并执行项目全部测试套件 |
| ./gradlew test --tests "com.example.CalculatorTest" | 仅运行指定测试类的全部测试方法 |
| ./gradlew test --tests "*CalculatorTest.addReturnsSumOfTwoNumbers" | 仅运行匹配指定类与方法名的单个用例 |
| ./gradlew test --info | 输出详细运行日志与标准输出便于定位失败 |
| ./gradlew test --rerun-tasks | 跳过 Gradle 增量缓存强制重跑测试 |
| ./gradlew clean test | 清空构建产物后完整重建并执行测试 |
运行离线 Python 校验:断言族、BeforeAll/BeforeTest 生命周期隔离、CSV 参数化与虚拟时钟 runTest
展开查看收起
"""Offline Kotlin 2.x semantic verifier for Chapter 41: Testing."""
import fnmatch
import json
VERSION = "CPython 3.12.14 offline Kotlin 2.x semantic verifier (kotlinc absent)"
class Calculator:
def add(self, a: int, b: int) -> int:
return a + b
def divide(self, a: int, b: int) -> int:
if b == 0:
raise ValueError("除数不能为 0")
return int(a / b)
def case_calculator_unit_tests_and_assertions():
calc = Calculator()
results = {}
# Emulate kotlin.test assertion suite
assert calc.add(2, 3) == 5 and calc.add(-1, 1) == 0
results["assertEquals"] = True
assert calc.add(2, 2) != 5
results["assertNotEquals"] = True
assert calc.divide(10, 2) > 0
results["assertTrue"] = True
assert not bool([])
results["assertFalse"] = True
sample_map = {"ok": 1}
assert sample_map.get("missing") is None
results["assertNull"] = True
assert sample_map.get("ok") is not None
results["assertNotNull"] = True
obj_a = [1, 2]
obj_b = obj_a
obj_c = [1, 2]
assert obj_a is obj_b and obj_a is not obj_c
results["assertSame_and_NotSame"] = True
assert 2 in [1, 2, 3]
results["assertContains"] = True
caught_msg = None
try:
calc.divide(10, 0)
except ValueError as exc:
caught_msg = str(exc)
results["assertFailsWith_msg"] = caught_msg
actual = results
expected = {
"assertEquals": True,
"assertNotEquals": True,
"assertTrue": True,
"assertFalse": True,
"assertNull": True,
"assertNotNull": True,
"assertSame_and_NotSame": True,
"assertContains": True,
"assertFailsWith_msg": "除数不能为 0",
}
return {
"name": "calculator_unit_tests_and_assertions",
"summary": "Verify all kotlin.test assertion helpers and assertFailsWith exception message check",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_lifecycle_isolation_and_parameterized_csv():
lifecycle_trace = []
sites: list[str] = []
def before_all():
lifecycle_trace.append("BeforeAll")
def after_all():
lifecycle_trace.append("AfterAll")
def before_test():
nonlocal sites
lifecycle_trace.append("BeforeTest")
sites = ["Alpha", "Beta"]
def after_test():
lifecycle_trace.append("AfterTest")
sites.clear()
def test_add_increases_size():
sites.append("mbsky.cn")
return len(sites)
def test_starts_with_two():
return len(sites)
before_all()
sizes = []
for test_fn in (test_add_increases_size, test_starts_with_two):
before_test()
sizes.append(test_fn())
after_test()
after_all()
# @ParameterizedTest + @CsvSource
calc = Calculator()
csv_rows = ["1, 2, 3", "0, 0, 0", "-1, 1, 0", "100, 200, 300"]
param_results = []
for row in csv_rows:
a, b, exp = (int(x.strip()) for x in row.split(","))
param_results.append(calc.add(a, b) == exp)
actual = {
"lifecycle_trace": lifecycle_trace,
"isolated_sizes": sizes,
"csv_case_count": len(param_results),
"csv_all_passed": all(param_results),
}
expected = {
"lifecycle_trace": [
"BeforeAll",
"BeforeTest",
"AfterTest",
"BeforeTest",
"AfterTest",
"AfterAll",
],
"isolated_sizes": [3, 2],
"csv_case_count": 4,
"csv_all_passed": True,
}
return {
"name": "lifecycle_isolation_and_parameterized_csv",
"summary": "Verify @BeforeAll/@BeforeTest/@AfterTest/@AfterAll isolation and 4-row @CsvSource execution",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_virtual_time_run_test_and_gradle_filter():
# Virtual time scheduler emulating kotlinx.coroutines.test.runTest
class VirtualTestScheduler:
def __init__(self):
self.current_time_ms = 0
def advance_time_by(self, ms: int) -> None:
self.current_time_ms += ms
scheduler = VirtualTestScheduler()
# suspend fun greet(name) { delay(1000); return "Hello, $name" }
scheduler.advance_time_by(1000)
greeting = "Hello, Kotlin"
# Gradle --tests pattern matching
all_tests = [
"com.example.CalculatorTest.addReturnsSumOfTwoNumbers",
"com.example.CalculatorTest.divideByZeroThrowsException",
"com.example.SiteTest.addSiteIncreasesSize",
]
cls_matched = [t for t in all_tests if t.startswith("com.example.CalculatorTest.")]
method_matched = [t for t in all_tests if fnmatch.fnmatch(t, "*CalculatorTest.addReturnsSumOfTwoNumbers")]
actual = {
"virtual_time_ms": scheduler.current_time_ms,
"greeting": greeting,
"class_filter_count": len(cls_matched),
"method_filter_matches": method_matched,
"junit5_requires_useJUnitPlatform": True,
}
expected = {
"virtual_time_ms": 1000,
"greeting": "Hello, Kotlin",
"class_filter_count": 2,
"method_filter_matches": ["com.example.CalculatorTest.addReturnsSumOfTwoNumbers"],
"junit5_requires_useJUnitPlatform": True,
}
return {
"name": "virtual_time_run_test_and_gradle_filter",
"summary": "Verify runTest virtual-time advancement without wall-clock sleep and Gradle --tests filters",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_calculator_unit_tests_and_assertions(),
case_lifecycle_isolation_and_parameterized_csv(),
case_virtual_time_run_test_and_gradle_filter(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
最常见原因是忘记在 build.gradle.kts 中声明 tasks.test { useJUnitPlatform() },导致 Gradle 默认沿用 JUnit 4 引擎而无法发现 JUnit 5 的测试方法;此外还需核查测试方法是否混用了错误包的 @Test 注解或未置于 src/test/kotlin 源码集内。