Rでのテストツール 〜 RUnit の紹介ページを見つけたのでメモ

RUnitについて、紹介されていたのでメモ。

RWikiも参考にして試してみた。


◎前提の設定
1.作成したテストコードのファイル名は「TestSample.R」、保存フォルダは「C:\bin\R\test」とした。
2.ワーキングディレクトリをテストコードの保存フォルダ「C:\bin\R\test」に変更する。

#Working Directoryの確認
> getwd()
[1] "C:/bin"

#Working Direcotryの変更
> setwd("C:/bin/R/test")
> getwd()
[1] "C:/bin/R/test"


①テストコードを作成してファイルに保存する。

#function that doubles the input to return
sampleFunction <- function(n){
}

#test function
test.sampleFunction <- function(){
 checkEqualsNumeric(sampleFunction(1),2);
}

②実行してみる

>runTestFile("TestSample.R")
Executing test function test.sampleFunction  ... Timing stopped at: 0 0 0 
Error in checkEqualsNumeric(sampleFunction(1), 2) : Modes: NULL, numeric
Lengths: 0, 1
target is NULL, current is numeric
 done successfully.

Number of test functions: 1 
Number of errors: 0 
Number of failures: 1 

テストが失敗したので、テスト対象の関数定義を見直して、修正する。
再度テストを実行する。

③テスト対象の修正

#function that doubles the input to return
sampleFunction <- function(n){
 return(n*2);
}

#test function
test.sampleFunction <- function(){
 checkEqualsNumeric(sampleFunction(1),2);
}

④テストの再実行
テストが成功。

> runTestFile("TestSample.R")
Executing test function test.sampleFunction  ...  done successfully.
Number of test functions: 1 
Number of errors: 0 
Number of failures: 0 


なお、RstudioのDevtoolsにtesttthatというものもあるらしい。