【发布时间】:2019-11-03 16:47:57
【问题描述】:
我有一个使用 testthat 的自动化测试包。但是,我想知道当一个人想要进行大量测试时,最佳实践是什么。一种常见的情况是,我正在测试所有参数/pars 是否都做了一些独特的事情。这是一个提供想法的非功能示例:
# GG_heatmap --------------------------------------------------------------
#save plots to list
heatmaps = list(
#various options
default = mtcars[, c(1,3,4,5,6,7)] %>% GG_heatmap(),
no_reorder = mtcars[, c(1,3,4,5,6,7)] %>% GG_heatmap(reorder_vars = F),
no_values = mtcars[, c(1,3,4,5,6,7)] %>% GG_heatmap(add_values = F),
many_digits = mtcars[, c(1,3,4,5,6,7)] %>% GG_heatmap(digits = 5)
)
test_that("GG_heatmap", {
#check that plots work
walk(heatmaps, ~expect_s3_class(., class = "ggplot"))
#check for non-identity
#cant think of an easy smart way to do this
expect_true(!identical(heatmaps$default, heatmaps$no_reorder))
expect_true(!identical(heatmaps$default, heatmaps$no_values))
expect_true(!identical(heatmaps$default, heatmaps$many_digits))
expect_true(!identical(heatmaps$no_reorder, heatmaps$no_values))
expect_true(!identical(heatmaps$no_reorder, heatmaps$many_digits))
expect_true(!identical(heatmaps$no_values, heatmaps$many_digits))
})
所以,有一个名为GG_heatmap()(即this one,稍作修改)的函数返回ggplot2 绘图。
在walk()中,我们只检查类是否正确。我试过了,当类错误时它确实失败了,执行devtools::test()时的测试摘要是正确的,即它发现walk()调用运行4个测试,而不是1个。
在下面的 6 个测试中,我检查每个绘图对象是否不同,即参数做了一些事情,所有这些都彼此不同。就我而言,由于我有 4 个版本,我需要测试 6 个(即choose(4, 2))组合以确保它们都是唯一的。如果我有 10 个参数要测试,这将是很多手动代码要编写 (choose(10, 2) = 45)。
所以我的问题是,在进行这样的测试时,最佳做法是什么?是否有一种功能可以测试每个对象的唯一性?我能想到的最好的方法是循环输出:
> gtools::combinations(4, 2)
[,1] [,2]
[1,] 1 2
[2,] 1 3
[3,] 1 4
[4,] 2 3
[5,] 2 4
[6,] 3 4
然后调用每一行:
expect_true(!identical(heatmaps[[v1]], heatmaps[[v2]]))
其中v1 和v2 指的是上列中的整数。
【问题讨论】:
-
我认为您的建议没有问题。
标签: r unit-testing testthat