【问题标题】:How is the setUp() method called before the invocation of each test method?在调用每个测试方法之前如何调用 setUp() 方法?
【发布时间】:2017-08-29 17:19:26
【问题描述】:

我正在阅读一本很棒的书,了解 Swift 中的测试驱动开发。我的最终目标是更好地理解 OOP 架构。在我阅读本书时,前面的一节指出,setUp() 方法在我理解的每个测试方法之前被触发,它会设置对象以运行测试以获得通过或失败结果。我不确定的是,从架构的角度来看,这怎么可能? Apple 是如何让一个类的方法在类中的所有其他方法之前被触发的?

这里是一些示例代码:

import XCTest
@testable import FirstDemo

class FirstDemoTests: XCTestCase {

    override func setUp() {
        super.setUp()
        // Put setup code here. This method is called before the invocation of each test method in the class.
    }

    override func tearDown() {
        // Put teardown code here. This method is called after the invocation of each test method in the class.
        super.tearDown()
    }

    func testExample() {
        // This is an example of a functional test case.
        // Use XCTAssert and related functions to verify your tests produce the correct results.
    }

    func testPerformanceExample() {
        // This is an example of a performance test case.
        self.measure {
            // Put the code you want to measure the time of here.
        }
    }

}

【问题讨论】:

    标签: ios swift oop xctest xctestcase


    【解决方案1】:

    对于每个要测试的测试:调用setup(),然后是实际测试,然后是teardown()

    然后再次从该类设置 另一个 测试并再次拆卸...直到您的测试类的所有**测试都运行。

    行的顺序不会影响首先调用哪个测试。

    这样做的原因是因为 2 个测试应该 100% 独立。您不希望 testExample 对正在执行测试的对象/sut/system_under_test 做某事(改变它的状态),但是, 撤消它所做的事情。否则,您的 testPerformanceExample 将从您不是的状态加载 期待。

    【讨论】:

      【解决方案2】:

      我认为 XCTest 类有一个生命周期,就像 UIViewController 一样。

      viewDidLoad()在视图加载到内存时在init(coder:)之后调用,setUp()方法也在测试类加载之后调用(在对象的生命周期内调用一次)。

      您还可以在 github 上调查原生和第三方测试框架源代码:

      https://github.com/apple/swift-corelibs-xctest

      https://github.com/google/googletest

      【讨论】:

      • 谢谢,如果是这样的话,那么我该如何理解 UIViewController 的方法是如何被触发的呢?例如,我相信 ViewDidLoad() 是由运行时环境自动触发的。但是我们所说的“自动”是什么意思,我在想某个地方的某些东西被编程来调用这个方法,我想知道在哪里可以了解更多关于它的信息。我希望这是有道理的
      【解决方案3】:

      您正在对一个名为 XCTestCase 的类进行子类化。通常,Testframework 会自省定义了测试方法的类,并以特定顺序运行它们。

      无论如何,我不能 100% 确定 XCTest 是否以这种方式工作,但您可以尝试查看源代码并尝试深入挖掘:

      https://github.com/apple/swift-corelibs-xctest

      【讨论】:

      • 谢谢,这是一个很好的观点,因为我忘记了 Swift 是开源的,但是我发现导航 github 存储库对于如何找到我感兴趣的区域有点令人困惑。关于此的任何提示?
      • 我不会试图理解整个源代码,只是通过在 git 中阅读它......我会尝试检查它并构建它。构建后,尝试在另一个项目中引用它,编写一些愚蠢的测试,以确保它可以正常工作。然后一起玩。稍微修改一下源代码,打破它,引入一些错误。重新编译一切,看看会发生什么。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-08
      • 1970-01-01
      • 2017-09-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多