4

我正在阅读一本很棒的书,了解 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.
        }
    }

}
4

3 回答 3

5

我认为XCTest类有一个生命周期UIViewController,例如。

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

您还可以在 github 上研究本机和第三方测试框架源代码:

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

https://github.com/google/googletest

于 2017-04-04T13:30:17.537 回答
2

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

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

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

于 2017-04-04T13:54:46.533 回答
2

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

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

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

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

于 2017-04-04T13:54:55.117 回答