我有一个bowtieIndex(bowtieBuildLocation, filename)
调用 bowtie2-build 的函数。它的参数是我系统上的 bowtie2-build 位置和输出文件名。
如何在不硬编码 bowtie2-build 位置的情况下为此功能编写测试?
如果您在函数内部所做的只是调用外部程序,那么您无法测试它是否直接有效。如果没有代码本身,这很难具体回答,但如果,例如,bowtieIndex
调用system
以运行外部程序,您可以模拟system
会做什么,假装它工作或失败。查看testthat::with_mock
.
以下是三个例子。第一个参数是将要执行的新代码,而不是真正的system
函数。如果您想做非常具体的事情,system
调用函数的参数在函数定义中可以正常使用。我发现重复测试比编写复杂的替换函数更容易。第二个参数中的所有内容,代码块 { },都在一个只看到替换系统函数的上下文中执行,包括所有嵌套函数调用。在此代码块之后,with_mock
函数退出并且 realbase::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" ))