mercredi 28 décembre 2016

How to test an abstract data type?

Suppose we have a module that defines an abstract type T:

module AbstractType (T, lexer) where

data T = T String deriving Show

lexer = (fmap T) . words

(Note that we do not export any type constructors for T, so the user would not be able to draft an instance by hand.)

How does one unit test lexer function?

Sure we may use the Show property of T, like this:

module Main where

import AbstractType

main = test
    (show $ lexer "summer is miles and miles away")
        "[T \"summer\",T \"is\",T \"miles\",T \"and\",T \"miles\",T \"away\"]"

test :: (Eq a) => a -> a -> IO ()
test expression expectation
    | expression == expectation = putStrLn "Test passed."
    | otherwise = error "Test failed."

— But this is both not beautiful and unfit for cases when our abstract type is not an instance of a class that permits casting to another, constructable type.

Is there a remedy?

Aucun commentaire:

Enregistrer un commentaire