簡體   English   中英

Haskell Tasty Unit Tests - 如何使用組和簡單的夾具來避免重復?

[英]Haskell Tasty Unit Tests - how to use groups and simple fixtures to avoid repetition?

您將如何編寫一個 Tasty HUnit 測試,該測試在單個測試中包含針對單個夾具變量的多個檢查,或者至少是一組整潔的此類測試?

例如,考慮這個 Gherkin 規范:

Scenario: A 3-Vector has x, y and z components
  Given: a <- Vec(1.0, 2.0, 3.0)
  Then: a.x = 1.0
  And a.y = 2.0
  And a.z = 3.0

我可以做這樣的事情,但它非常重復:

unitTests = testGroup "All Unit Tests"
  [ testCase "A 3-Vector has x, y and z components" $ assertEqual [] (x $ Vec 1.0 2.0 3.0) 1.0
  , testCase "A 3-Vector has x, y and z components" $ assertEqual [] (y $ Vec 1.0 2.0 3.0) 2.0
  , testCase "A 3-Vector has x, y and z components" $ assertEqual [] (z $ Vec 1.0 2.0 3.0) 3.0
  ]

我對此的擔憂是我已經重復了三次場景名稱,並且我還創建了三次夾具。 我想找到一種方法將所有三個斷言分組為一個標題為“A 3-Vector has x, y and z components”的組,並且只指定一次夾具 Vec。

我可以擴展測試規范以盡量減少一些描述重復,但如果可以的話,我寧願堅持 Gherkin 規范:

unitTests = testGroup "All Unit Tests"
  [ testCase "A 3-Vector has x component" $ assertEqual [] (x $ Vec 1.0 2.0 3.0) 1.0
  , testCase "A 3-Vector has y component" $ assertEqual [] (y $ Vec 1.0 2.0 3.0) 2.0
  , testCase "A 3-Vector has z component" $ assertEqual [] (z $ Vec 1.0 2.0 3.0) 3.0
  ]

我不知道為組定義一次 Vec 的方法。

我想做的是這樣的(不是真正的代碼:):

unitTests = testGroup "All Unit Tests"
  [ testScenario "A 3-Vector has x, y and z components" 
    let v = Vec 1.0 2.0 3.0 in
    [ testCase "x" assertEqual [] (x $ v) 1.0
    , testCase "y" assertEqual [] (y $ v) 2.0
    , testCase "z" assertEqual [] (z $ v) 3.0
    ]
  ]

感謝Joachim Breitner ,他建議我的“非真實代碼”並沒有離題太遠。 他是對的。

通過一些調整,我最終得到了這個,它可以按我的意願工作:

data Vec = Vec { x, y, z :: Double } deriving (Show)

unitTests = testGroup "All Unit Tests"
  [ testGroup "A 3-Vector has x, y and z components" $
    let v = Vec 1.0 2.0 3.0 in
    [ testCase "x" $ assertEqual [] (x v) 1.0
    , testCase "y" $ assertEqual [] (y v) 2.0
    , testCase "z" $ assertEqual [] (z v) 3.0
    ]
  ]

在一個 testCase 中有多個斷言是完全可以的。 所以你可以這樣做:

unitTests = testGroup "All Unit Tests"
  [ testCase "A 3-Vector has x, y and z components" $ do
    let v = Vec 1.0 2.0 3.0
    assertEqual [] (x v) 1.0
    assertEqual [] (y v) 2.0
    assertEqual [] (z v) 3.0
  ]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM