2017-04-06 40 views
6

我想用Stack設置現有的Haskell項目。現有項目使用test目錄下的多個文件;這些單獨的測試文件默認情況下,Stack(或cabal?)似乎使用單個test/Spec.hs進行測試。我怎樣才能繼續在這個項目中使用多個文件?如何使用Haskell堆棧項目運行多個測試文件

注意:我正在學習Haskell,這個項目通過「kata」方法接近我的學習。因此,測試是孤立的,一次只關注語言的一個方面。

+0

您可以在'.cabal'文件中配置堆棧的測試(和其他)行爲。查看測試部分 – Lazersmoke

+0

@Lazersmoke我知道'.cabal'文件中有一部分。你有沒有關於如何爲多個測試文件進行配置的例子?我還沒有找到一個明確的例子,因此提出了這個問題 – haiqus

回答

9

這裏是這樣

> 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 -folder獨立

的目錄結構的設置

首先你需要將測試套件添加到您的

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.hsCSpec.hs和你Spec.hstst/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(如果我忘記了一個,我最親愛的道歉 - 那些是我經常使用的道歉)。

相關問題