関数内で外部プログラムを呼び出しているだけの場合、それが直接機能するかどうかをテストすることはできません。コード自体がなければ、具体的に答えるのは難しいですが、たとえば、外部プログラムを実行するためにbowtieIndex
呼び出している場合は、機能したか失敗したかのように見せかけて、何をするかをモックできます。のドキュメントを参照してください。system
system
testthat::with_mock
以下に 3 つの例を示します。system
最初のパラメーターは、実際の関数の代わりに実行される新しいコードです。非常に具体的なことをしたい場合、system
関数が呼び出されたパラメーターは、関数定義で通常どおり使用できます。複雑な置換関数を記述するよりも、繰り返しテストする方が簡単だと思います。2 番目のパラメーターであるコード ブロック { } 内のすべてが、ネストされたすべての関数呼び出しを含む、置換システム関数のみを参照するコンテキストで実行されます。このコード ブロックの後、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" ))