Haskell unit testing

前端 未结 3 1708
小鲜肉
小鲜肉 2021-01-30 15:30

I\'m new to haskell and working on unit testing, however I find the ecosystem to be very confusing. I\'m confused as to the relationship between HTF and HUnit.

In som

3条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-30 16:08

    I'm also newbie haskeller and I've found this introduction really helpful: "Getting started with HUnit". To summarize, I'll put here simple testing example of HUnit usage without .cabal project file:

    Let's assume that we have module SafePrelude.hs:

    module SafePrelude where
    
    safeHead :: [a] -> Maybe a
    safeHead []    = Nothing
    safeHead (x:_) = Just x
    

    we can put tests into TestSafePrelude.hs as follows:

    module TestSafePrelude where
    
    import Test.HUnit
    import SafePrelude
    
    testSafeHeadForEmptyList :: Test
    testSafeHeadForEmptyList = 
        TestCase $ assertEqual "Should return Nothing for empty list"
                               Nothing (safeHead ([]::[Int]))
    
    testSafeHeadForNonEmptyList :: Test
    testSafeHeadForNonEmptyList =
        TestCase $ assertEqual "Should return (Just head) for non empty list" (Just 1)
                   (safeHead ([1]::[Int]))
    
    main :: IO Counts
    main = runTestTT $ TestList [testSafeHeadForEmptyList, testSafeHeadForNonEmptyList]
    

    Now it's easy to run tests using ghc:

    runghc TestSafePrelude.hs
    

    or hugs - in this case TestSafePrelude.hs has to be renamed to Main.hs (as far as I'm familiar with hugs) (don't forget to change module header too):

    runhugs Main.hs
    

    or any other haskell compiler ;-)

    Of course there is more then that in HUnit, so I really recommend to read suggested tutorial and library User's Guide.

提交回复
热议问题