R语言:对R包进行unit testing

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_38918949/article/details/82313390

R语言:对R包进行unit testing

Bioconductor给的官方unite testing介绍:
BioC-unite testing
这个介绍写了三件事:

  • how to write unit tests
  • how to run them
  • how they are woven into the standard Bioconductor build process

推荐使用两个package之一进行测试:RUnit和testthat,这里我选testthat。

下面是testthat的开发者Hadley Wickham写的文档和文章,此人还开发了ggplot。
testthat-文档
testthat-文章

是用testthat工具做unit test真的特别简单。在console输入代码:

devtools::use_testthat()

它会帮你:

  • 创建一个tests/testthat的文件路径
  • 在DESCRIPTION中添加一句:Suggests: testthat
  • 创建一个tests/testthat.R文件

然后你需要在tests/testthat下面创建R scrip文件,以test开头即可。然后在这个文件中,模仿下面的代码写unit tests,
代码内容是测试package stringr里面的str_length()函数。

context("String length")
library(stringr)

test_that("str_length is number of characters", {
    expect_equal(str_length("a"), 1)
    expect_equal(str_length("ab"), 2)
    expect_equal(str_length("abc"), 3)
})

简单来说,就是先写前两行代码,第一行给这个测试命名,第二行导入你的package,然后使用test_that()函数,这个函数的用法,在Hadley Wickham有详细介绍。

写完后用cmd/control + shift + T 或者在console输入:

devtools::test()

来进行测试。

下图是我的测试结果:

测试结果

扫描二维码关注公众号,回复: 3740164 查看本文章

猜你喜欢

转载自blog.csdn.net/sinat_38918949/article/details/82313390