2012-09-18 46 views
4

如何在RUnit中自动生成测试用例?在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文档,但在那里没什么相似之处。这里最好的解决方案是什么?

这是我怎么会(使用nosetest启动测试单元),它用Python语言编写:

for triplet in test_cases: 
    yield test_triplet(triplet) 

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

回答

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]) 
} 
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. 
+0

谢谢你, 问题这将不会被RUnit发射器看到。我忘了说我有另一个run_tests.R脚本,它解析目录中的所有脚本,识别名称以“test”开头的所有函数,并将它们作为测试执行。我认为这是在R中运行测试的标准方式,但也许我是蟒蛇偏向的。 – dalloliogm