HUnitの使い方(2)

MyTreeモジュールをHUnitでテストしながら作ってみます。ここの文章を読めば、HaskellでHUnitを使いながらモジュールを作る方法が分かります。ではまずテストを作ります。


$ghci
GHCi, version 6.10.1: http://www.haskell.org/ghc/ :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer ... linking ... done.
Loading package base ... linking ... done.
Prelude> :e test_tree.hs

module TreeTests where
import Test.HUnit
import MyTree
test1 ::Test
test1 = TestCase(assertEqual "" expected actual)
        where
                expected, actual ::[Int]
                expected = [1]
                actual = flatten (Leaf 1)
tests ::Test
tests = TestList [TestLabel "test1" test1]
main :: IO Counts
main = runTestTT tests

ロードするとコンパイルされますが、MyTreeが見つからないのでコンパイルに失敗します。


Prelude> :l test_tree.hs

test_tree.hs:3:7:
Could not find module `MyTree':
Use -v to see a list of the files searched for.
Failed, modules loaded: none.


MyTreeモジュールをtree.hsに作ります。

Prelude>:e tree.hs

module MyTree where
data Tree = Leaf Int
flatten :: Tree -> [Int]
flatten t = [1]

実装はとてもひどいですが、モジュールをテストする方法を確かめるのには十分です。
ロードし直して、テストを実行します。


Prelude> :l test_tree.hs tree.hs
[1 of 2] Compiling MyTree ( tree.hs, interpreted )
[2 of 2] Compiling TreeTests ( test_tree.hs, interpreted )
Ok, modules loaded: TreeTests, MyTree.
[star]TreeTests> main
Loading package HUnit-1.2.0.3 ... linking ... done.
Cases: 1 Tried: 1 Errors: 0 Failures: 0
Counts {cases = 1, tried = 1, errors = 0, failures = 0}

できました。