2012-09-18 101 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