[Haskell-cafe] HUnit and table-driven tests
Henk-Jan van Tuyl
hjgtuyl at chello.nl
Sun Aug 5 09:32:57 CEST 2012
On Sun, 05 Aug 2012 03:21:39 +0200, Matthew <wonderzombie at gmail.com> wrote:
> I've got a function which takes in two chars, describing a playing
> card and a suit. An example would be 4C or TH for a 4 of Clubs or a
> Ten of Hearts. I need to be able to compare the ranks of a card (e.g.
> a King is 13), so a Card is a tuple of rank and suit. The function
> which parses a Card is type String -> Maybe Card.
>
> I'm writing unit tests for this using HUnit, and ideally I'd go with a
> table-driven[1] approach, where each test case is a tuple of the input
> and the expected output. (Possibly I could expand this to a triple, or
> simply a list, to allow for an error message for each test case.) Then
> all the test function has to do is run through each case and assert as
> necessary. Example: [("TH", Just (Hearts, 10)), ("XH", Nothing)].
A simple solution:
> parseCard :: String -> Maybe Card
> parseCard string = <your function to test>
>test :: Bool
> test = all testEqual [("TH", Just (Hearts, 10)), ("XH", Nothing)]
> where
> testEqual (input, output) = parseCard input == output
For a description of 'all', see:
http://hackage.haskell.org/packages/archive/base/latest/doc/html/Prelude.html#v:all
Regards,
Henk-Jan van Tuyl
--
http://Van.Tuyl.eu/
http://members.chello.nl/hjgtuyl/tourdemonad.html
Haskell programming
--
More information about the Haskell-Cafe
mailing list