Testing a function that accepts an empty list
I am trying to write a unit test for a simple function that takes a list and just returns it,
func :: [a] -> [a]
func x = x
using test code to check that it works as expected with empty list
emptyListTest :: Test
emptyListTest = TestCase $ assertEqual "for (func [])," [] $ func []
main :: IO Counts
main = runTestTT $ TestList [emptyListTest]
However, I am getting the error
No instance for (Show a0) arising from a use of `assertEqual'
The type variable `a0' is ambiguous
Possible fix: add a type signature that fixes these type variable(s)
Note: there are several potential instances:
instance Show Double -- Defined in `GHC.Float'
instance Show Float -- Defined in `GHC.Float'
instance (Integral a, Show a) => Show (GHC.Real.Ratio a)
-- Defined in `GHC.Real'
...plus 28 others
In the expression: assertEqual "for (func [])," []
In the second argument of `($)', namely
`assertEqual "for (func [])," [] $ func []'
In the expression:
TestCase $ assertEqual "for (func [])," [] $ func []
Other tests with non-empty lists work fine and the function works fine when manually checked by calling func []
in ghci
.
I also noticed that if I create a dummy type and create a list that accepts elements of that type (if that's the correct way to say it) then passing that test seems to work and the test passes
data Dummy = Dummy
deriving(Eq, Show)
emptyList :: [Dummy]
emptyList = []
emptyListTest :: Test
emptyListTest = TestCase $ assertEqual "for (func [])," [] $ func emptyList
Why is this? Is there a way to test functions with an empty list without omitting the dummy type route?
source to share
Well, the error tells you exactly what is wrong. Read it.
The type variable `a0' is ambiguous
So, enter your variable! The GHC cannot know which type to use for testing if you don't.
emptyListTest = TestCase $ assertEqual "for (func [])," [] $ func ([] :: [Int])
You may need to enable an extension to make it inline.
source to share