unit-testing - 在测试期间访问由 `beforeAll` 设置的值

标签 unit-testing haskell hspec

这是我所拥有的:

spec :: Spec
spec = do
  manager <- runIO newManager

  it "foo" $ do
    -- code that uses manager

  it "bar" $ do
    -- code that usees manager
runIO 的文档建议我应该使用 beforeAll相反,因为我不需要 manager要构建规范树,我只需要它来运行每个测试,在我的用例中,最好让它们共享同一个管理器,而不是为每个测试创建一个新管理器。

If you do not need the result of the IO action to construct the spec tree, beforeAll may be more suitable for your use case.


beforeAll :: IO a -> SpecWith a -> Spec

但我不知道如何从测试中访问经理。
spec :: Spec
spec = beforeAll newManager go

go :: SpecWith Manager
go = do
  it "foo" $ do
    -- needs "manager" in scope
  it "bar" $ do
    -- needs "manager" in scope

最佳答案

规范参数作为常规函数参数传递给您的 it block (如果您想了解发生了什么,请查看 Example 类型类的关联类型)。一个完全独立的例子是:

import           Test.Hspec

main :: IO ()
main = hspec spec

spec :: Spec
spec = beforeAll (return "foo") $ do
  describe "something" $ do
    it "some behavior" $ \xs -> do
      xs `shouldBe` "foo"

    it "some other behavior" $ \xs -> do
      xs `shouldBe` "foo"

关于unit-testing - 在测试期间访问由 `beforeAll` 设置的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30536294/

相关文章:

ios - OCMockito 是否在 verify() 调用后重置调用计数?

c - C 程序的单元测试

haskell - `forkIO` 和 `putMVar` : what's going on under the hood?

haskell - 测试阅读器monad是否在错误的环境中被调用

haskell - 使用 MonadIO 测试类型类 : "No instance nor default method" error

angularjs - 如何使用 gitlab-ci-multi-runner 在 GitLab CI 中自动运行测试

unit-testing - 用于单元测试 Jersey Restful Web 服务的最佳 API/lib?

haskell - Haskell 类型系统中的问题

loops - while 循环中的错误

haskell - 将 HSpec 与堆栈结合使用