![](/img/trans.png)
[英]“Could not find module ‘Test.HUnit’” Error when executing Haskell's unittest (HUnit) in CodeRunner
[英]Haskell unit test for ErrorCall in HUnit
我有一个功能:
unify :: [Constraint] -> [Substitution]
在某些情况下,它会抛出error
函数的异常:
error "Circular constraint"
我正在使用Test.HUnit
进行单元测试,我想制作一个测试用例,断言这些错误会抛出某些输入。 我找到了这个 ,它提供了一种测试作为Eq
实例的异常的方法,但是error
似乎给出了一个ErrorCall
异常 ,它不是Eq
的实例,所以我得到了错误:
No instance for (Eq ErrorCall)
arising from a use of `assertException'
如何编写一个断言调用error
并且(最好)检查消息的TestCase
?
理想情况下,我会将您的功能重构为
unify' :: [Constraint] -> Maybe [Substitution]
unify' = -- your original function, but return Nothing instead of calling error,
-- and return Just x when your original function would return x
unify = fromMaybe (error "Circular constraint") . unify'
然后我会测试unify'
而不是测试unify
。
如果有多个可能的错误消息,我会像这样重构它:
unify' :: [Constraint] -> Either String [Substitution]
-- and return Left foo instead of calling error foo
unify = either error id . unify'
(顺便说一句,如果这是其他程序员将使用的库,他们中的一些人宁愿调用unify'
而不是部分函数unify
。)
如果您无法重构代码,我将修改您链接到的代码,将assertException
替换为:
assertErrorCall :: String -> IO a -> IO ()
assertErrorCall desiredErrorMessage action
= handleJust isWanted (const $ return ()) $ do
action
assertFailure $ "Expected exception: " ++ desiredErrorMessage
where isWanted (ErrorCall actualErrorMessage)
= guard $ actualErrorMessage == desiredErrorMessage
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.