与quickcheck如何支持反例类似:
property \x ->
counterexample ("Foo failed with: " ++ ...) $
foo x
但是它与shouldBe
一起使用,例如
failDetails (" details: " ++ baz a) $
a `shouldBe` 2
我希望它能打印出以下内容:
expected: 2
but got: 3
details: ...
答案 0 :(得分:4)
是的,似乎有可能:
import Control.Exception
import Test.HUnit.Lang (HUnitFailure(..))
failDetails details assert = do
assert `catch` \(HUnitFailure loc msg) -> do
throw $ HUnitFailure loc $ msg ++ "\n" ++ details
我们捕获shouldBe
引发的异常,修改消息并重新抛出它。
我们甚至可以像:
一样使用它1 `shouldBe` 2
$> failDetails "foobar"
如果我们定义:
($>) = flip ($)
infixl 0 $>
{-# INLINE ($>) #-}
答案 1 :(得分:0)
受@Wizek答案的启发,以下版本适用于较新版本的HUnit,适用于Selenium / WebDriver。
它适当地解包和重新包装FailureReason的不同构造函数
主要区别在于Control.Monad.Catch的使用,它使您可以使用WD而不是IO。
也不需要编写$>
运算符-Data.Function中已经有&
import Test.HUnit.Lang
import Control.Monad.Catch
import qualified Data.Text as Text
import Data.Function ((&))
failDetails :: Text -> WD () -> WD ()
failDetails textMessage expectation =
expectation `catch` \(HUnitFailure loc reason) ->
throwM $ HUnitFailure loc $ addMessageTo reason
where
message :: String
message = Text.unpack textMessage
addMessageTo :: FailureReason -> FailureReason
addMessageTo (Reason reason) = Reason $ reason ++ "\n" ++ message
addMessageTo (ExpectedButGot preface expected actual) =
ExpectedButGot newPreface expected actual
where
newPreface =
case preface of
Nothing -> Just message
Just existingMessage -> Just $ existingMessage ++ "\n" ++ message