使用 testthat 进行单元测试
编写 test_that() 代码块,使用断言,并通过 devtools::test() 运行测试
使用 testthat 进行单元测试 是 CoddyKit 上的免费 R Academy 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 R Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 R Academy 课程共包含 4 节课。
为什么要进行单元测试?
单元测试会自动验证各个函数是否正常运行。代码发生变化时,它们可以发现回归问题;同时还能作为可执行文档,让您更有信心安全地重构代码。testthat 程序包是 R 程序包的标准测试框架。
设置 testthat
usethis::use_testthat() 会将 testthat 添加到 DESCRIPTION 的 Suggests 中,创建 tests/testthat/,并创建测试运行脚本 tests/testthat.R。初始化新程序包时运行一次即可。
# usethis::use_testthat()
#
# Creates:
# tests/
# testthat.R <- runner (do not edit)
# testthat/
# (empty — write test files here)
#
# Updates DESCRIPTION:
# Suggests: testthat (>= 3.0.0)
# Config/testthat/edition: 3创建测试文件
usethis::use_test('add') 会创建 tests/testthat/test-add.R。按照惯例,测试文件命名为 test-{function_name}.R。每个文件集中包含针对一个函数或功能的测试。
# usethis::use_test('add') # creates tests/testthat/test-add.R
#
# Content of test-add.R:
# test_that('add() returns correct sum', {
# expect_equal(add(1, 2), 3)
# expect_equal(add(-1, 1), 0)
# expect_equal(add(0.1, 0.2), 0.3, tolerance = 1e-7)
# })test_that() 结构
test_that('description', { ... }) 用于将相关的期望分组。描述字符串应能补全句子“测试……”,并且要足够具体,以便在失败消息中提供有用信息。
# Good test_that descriptions:
# test_that('add() handles negative numbers', { ... })
# test_that('add() recycles length-1 vectors', { ... })
# test_that('add() returns NA when input contains NA', { ... })
#
# Bad (too vague):
# test_that('it works', { ... })
# test_that('test1', { ... })expect_equal() 和 expect_identical()
expect_equal(actual, expected) 会使用数值容差对浮点数进行测试。expect_identical(actual, expected) 要求完全相等,包括类型也必须相同。在大多数情况下,expect_equal() 更为合适。
# test_that('add() adds correctly', {
# expect_equal(add(1, 2), 3) # numeric equality
# expect_equal(add(0.1, 0.2), 0.3) # tolerance handles floating point
# expect_identical(add(1L, 2L), 3L) # exact type match: integer
# expect_identical(add(1.0, 2.0), 3.0) # exact type match: double
# })expect_error() 和 expect_warning()
测试函数是否产生正确的错误和警告。传入正则表达式模式来匹配错误消息 — 这样可以确保抛出的是正确的错误,而不只是任意错误。
# test_that('add() validates input types', {
# expect_error(
# add('a', 2),
# regexp = 'numeric' # message must contain 'numeric'
# )
# expect_error(
# add(NULL, 1),
# regexp = 'numeric'
# )
# })
#
# test_that('sqrt() warns on negative input', {
# expect_warning(sqrt(-1))
# })expect_true() 和 expect_false()
expect_true(expr) 和 expect_false(expr) 用于测试逻辑条件。当测试返回单个逻辑值的谓词或条件时,请使用它们。
# test_that('is_positive() returns correct logical', {
# expect_true(is_positive(5))
# expect_true(is_positive(0.001))
# expect_false(is_positive(0))
# expect_false(is_positive(-3))
# })
#
# # Also useful for vector tests:
# test_that('add() result has correct length', {
# result <- add(c(1,2,3), c(4,5,6))
# expect_true(length(result) == 3)
# })更多期望函数
testthat 针对不同场景提供了许多期望函数:
expect_length(x, n)— 检查向量长度expect_type(x, 'double')— 检查基本类型expect_s3_class(x, 'data.frame')— 检查 S3 类expect_null(x)— 检查是否为 NULLexpect_match(string, regexp)— 检查字符串模式
# test_that('add() output has correct type and length', {
# result <- add(c(1.0, 2.0), c(3.0, 4.0))
# expect_type(result, 'double')
# expect_length(result, 2)
# })
#
# test_that('summary_stats() returns a data frame', {
# result <- summary_stats(rnorm(100))
# expect_s3_class(result, 'data.frame')
# })使用 devtools::test() 运行测试
devtools::test()(Ctrl+Shift+T)会运行所有测试文件,并显示通过、失败和警告的摘要。单个测试失败时,会显示失败的期望以及实际值与预期值。
# devtools::test()
#
# Example output:
# == Testing mypackage ====================================
# v | OK F W S | Context
# v | 3 | add [0.1s]
# v | 4 | subtract [0.1s]
# x | 2 1 | multiply [0.2s]
# -- Failure (test-multiply.R:5): multiply() handles zero
# multiply(5, 0) not equal to 0.
# Actual: 5
# Expected: 0
# ==========================================================
# [ FAIL 1 | WARN 0 | SKIP 0 | PASS 9 ]使用 covr 测量测试覆盖率
covr::package_coverage() 会测量测试执行了程序包中多少百分比的代码行。covr::report() 会打开 HTML 报告,以绿色显示已覆盖的行,以红色显示未覆盖的行。目标是至少达到 80% 的覆盖率。
# library(covr)
# cov <- package_coverage()
# print(cov)
#
# Example output:
# mypackage Coverage: 87.50%
# R/add.R: 100.00%
# R/subtract.R: 100.00%
# R/utils.R: 62.50% <- needs more tests!
#
# covr::report() # interactive HTML report
# covr::zero_coverage(cov) # list uncovered lines测试边界情况
良好的测试不仅要覆盖正常路径,还要覆盖边界情况:
- 空输入:
numeric(0)、character(0) - NA 输入:函数会传递 NA,还是会处理 NA?
- 长度为 1 的输入与长度为 n 的输入
- 边界值:0、负数、非常大的值
- 错误类型:当用户向数值函数传入字符串时会发生什么?
# test_that('add() handles edge cases', {
# expect_equal(add(numeric(0), numeric(0)), numeric(0)) # empty
# expect_true(is.na(add(NA, 1))) # NA propagation
# expect_equal(add(1, c(1,2,3)), c(2,3,4)) # recycling
# expect_equal(add(.Machine$integer.max, 0L), # boundary
# .Machine$integer.max)
# })快速检查:expect_error()
您调用了 expect_error(my_fn('bad'), regexp = 'invalid input')。这个测试验证了什么?
单元测试回顾
使用 testthat 测试 R 包:
usethis::use_testthat()— 一次性设置测试基础设施usethis::use_test('fn')— 创建tests/testthat/test-fn.Rtest_that('description', {...})— 将相关预期分组expect_equal()、expect_error()、expect_warning()、expect_true()、expect_false()— 核心预期函数devtools::test()— 运行所有测试(Ctrl+Shift+T)covr::package_coverage()— 测量测试覆盖率
常见问题解答
「使用 testthat 进行单元测试」课时是免费的吗?
是的 — 「使用 testthat 进行单元测试」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 R Academy 课程的其余内容,请升级到 CoddyKit PRO。 R Academy 课程共包含 4 节课。
「使用 testthat 进行单元测试」这节课中我会学到什么?
编写 test_that() 代码块,使用断言,并通过 devtools::test() 运行测试 你通过在浏览器中直接运行的动手代码来练习 R Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 R Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 R Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。
「使用 testthat 进行单元测试」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 R Academy 课中编写并运行代码吗?
能。每节 R Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 使用 usethis 和 devtools 组织软件包结构
- 使用 roxygen2 编写函数文档
- 使用 testthat 进行单元测试
- CRAN 提交与软件包维护