gpt4 book ai didi

r - 在 RUnit 或 testthat 中自动生成测试用例

转载 作者:行者123 更新时间:2023-11-28 19:52:46 24 4
gpt4 key购买 nike

如何在 RUnit 中自动生成测试用例?

例如,假设我有一个简单的 sum() 函数:

sum <- function(x, y) {
return (x + y)
}

我想在一系列不同的测试用例上测试这个函数:

test_cases <- c( c(2, 2, 4),
c(3, 3, 6),
c(0, 0, 0),
c(-1, 2, 1)
)

每个向量的前两个元素是 x 和 y,第三个是 sum(x,y) 函数的预期输出。

在 python 中,我可以轻松编写一个函数,为 test_cases 中的每个元素生成一个测试用例,但我不知道如何在 R 中实现它。我查看了 RUnit 和 testthat 文档,但是有没有什么相似之处。这里最好的解决方案是什么?

这就是我用 python 编写它的方式(使用 nosetest 启动测试单元):

for triplet in test_cases:
yield test_triplet(triplet)

def test_triplet(triplet):
assert(sum(triplet[0], triplet[1]) == triplet[2])

最佳答案

# You simply take advantage of R's vector orientation.
test_cases <- matrix(c(2, 2, 4,
3, 3, 6,
0, 0, 0,
-1, 2, 1), ncol = 3, byrow = TRUE)
my_sum <- function(x, y) { x + y}

## testthat
library(testthat)
expect_equal(my_sum(test_cases[ , 1], test_cases[ , 2]), test_cases[ , 3])

## RUnit
library(RUnit)
test_my_sum <- function() {
checkEquals(my_sum(test_cases[ , 1], test_cases[ , 2]), test_cases[ , 3])
}

关于r - 在 RUnit 或 testthat 中自动生成测试用例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12479713/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com