我有一个函数bowtieIndex(bowtieBuildLocation, filename),它调用bowtie2-build。它的参数是在我的系统上的bowtie2 2构建位置和输出文件名。
如何在不对bowtie2 2构建位置进行硬编码的情况下为该函数编写测试?
发布于 2016-03-02 23:47:54
如果您在函数中所做的一切都是调用外部程序,那么您就不能直接测试它是否有效。如果没有代码本身,这很难具体回答,但是,例如,如果bowtieIndex调用system来运行外部程序,您可以模拟system将做什么,假装它工作了,或者失败了。查看testthat::with_mock的文档。
下面是三个例子。第一个参数是将执行的新代码,而不是真正的system函数。使用system函数调用的参数在函数定义中可以正常使用,如果您想要做非常具体的事情的话。我发现重复测试比编写复杂的替换函数更容易。第二个参数(代码块{ } )中的所有内容都是使用只看到替换系统函数(包括所有嵌套函数)的上下文执行的。在这个代码块之后,with_mock函数退出,真正的base::system自动返回作用域。哪些函数可以被模拟有一些限制,但是大量的基本函数可以被覆盖。
# Pretend that the system call exited with a specific error
with_mock(
`base::system`= function(...) {
stop("It didn't work");
}, {
expect_error( bowtieIndex( bowtieBuildLocation, filename ),
"It didn't work"
)
})
# Pretend that the system call exited with a specific return value
with_mock(
`base::system`= function(...) {
return(127);
}, {
expect_error( bowtieIndex( bowtieBuildLocation, filename ),
"Error from your function on bad return value." )
expect_false( file.exists( "someNotGeneratedFile" ))
})
# Pretend that the system call worked in a specific way
with_mock(
`base::system`= function(...) {
file.create("someGeneratedFile")
return(0);
}, {
# No error
expect_error( got <- bowtieIndex(bowtieBuildLocation, filename), NA )
# File was created
expect_true( file.exists( "someGeneratedFile" ))
})
# got variable holding results is actually available here, outside
# with_mock, so don't need to test everything within the function.
test_equal( got, c( "I", "was", "returned" ))https://stackoverflow.com/questions/35177396
复制相似问题