这是一个这样的目录结构的设置
> tree
.
├── example.cabal
├── app
│ └── Main.hs
├── ChangeLog.md
├── LICENSE
├── Setup.hs
├── src
│ ├── A
│ │ └── C.hs
│ ├── A.hs
│ └── B.hs
├── stack.yaml
└── tst
├── integration
│ └── Spec.hs
└── unit
├── A
│ └── CSpec.hs
├── ASpec.hs
├── BSpec.hs
└── Spec.hs
您希望有与通常的单元测试分开的集成测试以及与src-文件夹中的每个模块相对应的几个子模块
首先您需要将测试套件添加到您的
example.cabal文件
name: example
...
-- copyright:
-- category:
build-type: Simple
extra-source-files: ChangeLog.md
cabal-version: >=1.10
executable testmain
main-is: Main.hs
hs-source-dirs: app
build-depends: base
, example
library
exposed-modules: A.C,A,B
-- other-modules:
-- other-extensions:
build-depends: base >=4.9 && <4.10
hs-source-dirs: src
default-language: Haskell2010
test-suite unit-tests
type: exitcode-stdio-1.0
main-is: Spec.hs
hs-source-dirs: tst/unit
build-depends: base
, example
, hspec
, hspec-discover
, ...
test-suite integration-tests
type: exitcode-stdio-1.0
main-is: Spec.hs
hs-source-dirs: tst/integration
build-depends: base
, example
, hspec
, ...
将以下内容放入您的tst/unit/Spec.hs,它来自hspec-discover,它会发现(因此得名)...Spec.hs 形式的所有模块,并从每个模块中执行spec 函数。
tst/unit/Spec.hs
{-# OPTIONS_GHC -F -pgmF hspec-discover #-}
就这一行
其他测试文件
然后将您的单元测试添加到您的ASpec.hs,将其他单元测试添加到BSpec.hs、CSpec.hs 和您的Spec.hs 中的tst/integration 文件夹
module ASpec where
import Test.Hspec
import A
spec :: Spec
spec = do
describe "Prelude.head" $ do
it "returns the first element of a list" $ do
head [23 ..] `shouldBe` (23 :: Int)
it "returns the first element of an *arbitrary* list" $
property $ \x xs -> head (x:xs) == (x :: Int)
it "throws an exception if used with an empty list" $ do
evaluate (head []) `shouldThrow` anyException
然后你可以编译并运行你的测试
$> stack test
# now all your tests are executed
$> stack test :unit-tests
# now only the unit tests run
$> stack test :integration-tests
# now only the integration tests run
来源
您可以在https://hspec.github.io 找到所有示例,如果您想了解有关 hspec 样式测试的更多信息,我想最好从那里开始。对于堆栈 - 转到 https://haskellstack.org - 那里有一些关于测试/基准测试的信息 - 我的意思是关于运行测试和基准测试。
有关 haskell 中不同的测试风格,请参阅 HUnit、QuickCheck、Smallcheck、doctests(如果我忘记了,最诚挚的歉意 - 这些也是我经常使用的)。