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

时间:2012-09-18 15:03:46

标签: r testing runit testthat

如何在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])

2 个答案:

答案 0 :(得分:2)

sapply可能有用

Sum <- function(x, y) {  # Sum is much better than sum,this avoids problems with sum base function
  return (x + y)
}

test_cases <- matrix( c(2, 2, 4,  # I think a matrix structure is better to handle this problem
                        3, 3, 6,
                        0, 0, 0,
                        -1, 2, 1), ncol=3, byrow=TRUE)

# Applying your function and comparing the result with the expected result.
sapply(1:nrow(test_cases), function(i) Sum(test_cases[i,1], test_cases[i,2]))==test_cases[,3]

TRUE TRUE TRUE TRUE  # indicates the result is as expected.

答案 1 :(得分: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])
}