在Kiwi / Quick测试框架中使用beforeEach方法有什么用?

时间:2017-10-25 09:29:50

标签: swift unit-testing

为什么beforeEach在像Kiwi和Quick这样的测试框架中使用?

beforeEach {
            let storyboard = UIStoryboard(name: "Main",
                bundle: NSBundle(forClass: self.dynamicType))
            let navigationController = storyboard.instantiateInitialViewController() as UINavigationController
            viewController = navigationController.topViewController as ViewController

            UIApplication.sharedApplication().keyWindow!.rootViewController = navigationController
            let _ = navigationController.view
            let _ = viewController.view
        }

示例代码取自:https://www.natashatherobot.com/unit-testing-in-swift-a-quick-look-at-quick/

1 个答案:

答案 0 :(得分:1)

相当于Apple的测试框架setUp method。它在每次测试之前执行,以设置将在每次测试中使用的组件和模拟。

根据Kiwi的wiki

  

beforeEach(aBlock)在所有封闭的上下文中的每个块之前运行。实际设置特定上下文的代码应该放在这里。

避免代码重复是有帮助的,并且测试中有一个标准的设置。

在您分享的代码段中,beforeEach方法正在设置UINavigationController,其中rootViewController从故事板中提取。它还加载了视图,因此测试可以访问诸如outlet之类的组件。