F#のUnitTest Framework FsUnit
FsUnit
http://fsunit.codeplex.com/
NUnitの機能を使う。なのでNUnitも別途インストールします。*1
FsUnit本体のコードはたったのこれだけ。
http://fsunit.codeplex.com/sourcecontrol/network/Show?projectName=fsunit&changeSetId=7611206edf25#SourceCode%2fFsUnit.NUnit%2fFsUnit.fs
使い方は上記のFsUnitのトップページに載っているのですが、テストコードのクラス名、メソッド名がファンキーです。
文章…(・・?
type LightBulb(state) = member x.On = state override x.ToString() = match x.On with | true -> "On" | false -> "Off" [<TestFixture>] type ``Given a LightBulb that has had its state set to true`` ()= let lightBulb = new LightBulb(true) [<Test>] member test. ``when I ask whether it is On it answers true.`` ()= lightBulb.On |> should be True [<Test>] member test. ``when I convert it to a string it becomes "On".`` ()= string lightBulb |> should equal "On"
自作のプログラムを対象に簡単なテストコードを書いてみます。
テスト対象のクラスのコードはこれ。
http://github.com/hayashih/EpubCreator/blob/master/EpubCreator.fs
テストコード
[<TestFixture>] type ``EpubCreator Test`` ()= let epub = new Name.hayashih.Epub.EpubCreator() //do epub.Author <- "hayashih" // 成功する場合 do epub.Author <- "nanashi no gonbei" // 失敗する場合 [<Test>] member x. ``Check author.`` ()= epub.Author |> should equal "hayashih" let Main() = try let test = ``EpubCreator Test`` () test.``Check author.`` () with | :? NUnit.Framework.AssertionException as ex -> printfn "%s" ex.Message; [<STAThread>] do Main()
成功の場合は何も起こりませんが、失敗した場合は例外でNUnit.Framework.AssertionExceptionがきます。上記のように捕まえてエラーメッセージを表示すると
Expected string length 8 but was 17. Strings differ at index 0. Expected: "hayashih" But was: "nanashi no gonbei" -----------^
という表示ができます。
*1:MbUnit http://www.mbunit.com/ というテストフレームワークと組み合わせることもできるらしい。