通常,任何重要的Haskell项目都使用Cabal进行管理。Cabal可以负责构建、分发、文档化(借助haddock)和测试。
标准做法是将测试文件放在test
目录下,并在.cabal
文件中设置一个测试套件。详见用户手册。这是我某个项目的测试套件的样子:
Test-Suite test-melody
type: exitcode-stdio-1.0
main-is: Main.hs
hs-source-dirs: test
build-depends: base >=4.6 && <4.7,
test-framework,
test-framework-hunit,
HUnit,
containers == 0.5.*
然后在文件test/Main.hs
中。
import Test.HUnit
import Test.Framework
import Test.Framework.Providers.HUnit
import Data.Monoid
import Control.Monad
import Utils
pushTest :: Assertion
pushTest = [NumLit 1] ^? push (NumLit 1)
pushPopTest :: Assertion
pushPopTest = [] ^? (push (NumLit 0) >> void pop)
main :: IO ()
main = defaultMainWithOpts
[testCase "push" pushTest
,testCase "push-pop" pushPopTest]
mempty
Utils
定义了一些比 HUnit 更友好的接口。
对于轻量级测试,我强烈建议您使用 QuickCheck。它可以让您编写简短的属性并在一系列随机输入上进行测试。例如:
import Test.QuickCheck
prop_reverseReverse :: [Int] -> Bool
prop_reverseReverse xs = reverse (reverse xs) == xs
然后
$ ghci Tests.hs
> import Test.QuickCheck
> quickCheck prop_reverseReverse
.... Passed Tests (100/100)
tasty
而不是test-framework
(HTF?),但我也看到HTF在几个月的沉寂后上周进行了小更新。 - misterbee