如何在R中制作单元测试块?

时间:2015-07-17 09:19:13

标签: r unit-testing

我已经开始使用svUnit(docs)对R中的函数进行单元测试。我已经对文件中的函数进行了测试,然后对另一个文件中的函数进行了测试,我创建了一个mainTest,在那里我调用了所有的测试。所以我的项目看起来像这样:

proj
 |-src
 | |-functions1 (containing some functions)
 | |-functions2 (containing some other functions)
 | |-functions3 (containing some more functions)
 | |-mainFile (here I call the functions in the files above)
 |-tests
   |-functions1Test (containing tests for functions in functions1 file)
   |-functions2Test (containing tests for functions in functions2 file)
   |-functions3Test (containing tests for functions in functions3 file)
   |-mainTest (containing the function that runs all the tests)

functionsXTest文件如下所示:

source('functionsX.R')

test(fun1) <- function(){
   # call the fun1 function and check the result
}


test(fun2) <- function(){
   # call the fun2 function and check the result
}

# ...

functions1Tests <- svSuite(svSuiteList()) # here

mainTests看起来像这样:

library('svUnit')

source('functions1Tests.R')
source('functions1Tests.R')
source('functions1Tests.R')

launchTests <- function(){
   clearLog()

   runTest(functions1Tests)
   runTest(functions2Tests)
   runTest(functions3Tests)

   Log()
}

我认为文件functionsXTest.R末尾的最后一行是将单元测试分组到变量中,但似乎它正在对该变量中的所有测试进行分组,因此functions1Tests包含所有测试functions1.R和functions2Tests中的函数包含functions1.R和functions2.R中的测试。是否有可能将文件中的所有测试分组到变量中并对每个变量运行测试,以便更容易找到有问题的测试?

1 个答案:

答案 0 :(得分:0)

我发现如果我在svSuite中添加测试的名称,它会将不同的测试分开,所以这样做:

functions1Tests <- svSuite("fun1", "fun2")

在functionsXTest.R文件的最后一行,functions2Tests将不包含functions1Test.R的测试。

但现在我想知道是否有可能在日志中拆分测试,因为现在它将显示如下内容:

> launchTests()
= A svUnit test suite run in less than 0.1 sec with:

* testfun1 ... OK
* testfun1 ... OK
* testfun2 ... OK
* ...

== testfun1 (in runitfunctions1Test.R) run in less than 0.1 sec: OK
//Pass: 7 Fail: 0 Errors: 0//

== testfun1 (in runitfunctions2Test.R) run in less than 0.1 sec: OK
//Pass: 4 Fail: 0 Errors: 0//

== testfun2 (in runitfunctions1Test.R) run in less than 0.1 sec: OK
//Pass: 10 Fail: 0 Errors: 0//
...