【问题标题】:automatically generate test cases in RUnit or testthat在 RUnit 或 testthat 中自动生成测试用例
【发布时间】:2012-09-10 21:02:24
【问题描述】:

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

【问题讨论】:

    标签: r testing runit testthat


    【解决方案1】:
    # 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.
      

      【讨论】:

      • 谢谢,问题是 RUnit 启动器看不到这个。我忘了说我还有另一个run_tests.R脚本,它解析一个目录中的所有脚本,识别所有名称以“test.”开头的函数,并将它们作为测试执行。我认为这是在 R 中运行测试的标准方式,但也许我偏向于 python。
      猜你喜欢
      • 2016-03-08
      • 1970-01-01
      • 2014-04-10
      • 1970-01-01
      • 1970-01-01
      • 2023-03-24
      • 2015-10-11
      • 2018-10-30
      • 2023-03-30
      相关资源
      最近更新 更多