简体   繁体   English

简单的haskell单元测试

[英]Simple haskell unit testing

I want to go through 99 Haskell Problems , and I want to concentrate on the solution but with testing. 我想通过99个Haskell问题 ,我想专注于解决方案,但需要测试。 If I have the solution to the first problem as a 3 line .hs file, 如果我将第一个问题的解决方案作为3行.hs文件,

myLast :: [a] -> a
myLast [x] = x
myLast (_:xs) = myLast xs

What is the minimal amount of code I can add to this so that I can add tests inline and run them with runhaskell ? 我可以添加的最小代码量是多少,以便我可以在线添加测试并使用runhaskell运行它们?

QuickCheck (which basicaly generates test inputs for you) is probably the best way to test pure function. 快速检查 (你这basicaly生成测试输入)可能是测试纯函数的最佳方式。 And if a function in question has an analog from the standard library you can just test your function using the standard one as a model: 如果有问题的函数具有标准库中的模拟,您可以使用标准函数作为模型来测试函数:

{-# LANGUAGE TemplateHaskell #-}

import Test.QuickCheck
import Test.QuickCheck.All

myLast :: [a] -> a
myLast [x] = x
myLast (_:xs) = myLast xs

-- here we specify that 'myLast' should return exactly the same result
-- as 'last' for any given 'xs'
prop_myLast xs = myLast xs == last xs


return [] -- need this for GHC 7.8
-- quickCheckAll generates test cases for all 'prop_*' properties
main = $(quickCheckAll)

If you run it you'll get: 如果你运行它,你会得到:

=== prop_myLast on tmp3.hs:12 ===
*** Failed! Exception: 'tmp3.hs:(7,1)-(8,25): Non-exhaustive patterns in function myLast' (after 1 test):  
[]
False

because your myLast doesn't handle [] case (it should but should probably throw an error like 'last'). 因为你的myLast没有处理[]情况(它应该但应该抛出像'last'这样的错误)。 But here we can simply adjust our test but specifying that only non-empty strings should be used (using ==> combinator): 但是在这里我们可以简单地调整我们的测试,但是指定只应该使用非空字符串(使用==>组合器):

prop_myLast xs = length xs > 0 ==> myLast xs == last xs

Which makes all 100 auto-generated test cases to pass for myLast : 这使得所有100个自动生成的测试用例都可以通过myLast

=== prop_myLast on tmp3.hs:11 ===
+++ OK, passed 100 tests.
True

PS Another way to specify myLast behavior may be: PS另一种指定myLast行为的方法可能是:

prop_myLast2 x xs = myLast (xs++[x]) == x

Or better: 或更好:

prop_myLast3 x xs = x `notElem` xs ==> myLast (xs++[x]) == x

hspec is also a testing framework for Haskell, which is inspired by Ruby RSpec. hspec也是Haskell的测试框架,受Ruby RSpec的启发。 It integrates with QuickCheck, SmallCheck, and HUnit. 它集成了QuickCheck,SmallCheck和HUnit。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM