2

我知道一个类是未来对象的蓝图,我正在尝试使用 Swift 更好地掌握 OOP 架构。所以我的问题是,从类和实例的角度运行测试时会发生什么过程。我认为我实际上并没有必要创建我的 XCTestCase 子类的实例,但 Xcode 似乎会自动执行此操作。当我正在构建更多激情项目应用程序时,我通常必须创建一个实例才能使用它,但在测试中我没有那种感觉,它只是通过点击 (Command + U) 来工作。我想了解是否甚至创建了一个实例,如果是这样,如何创建?

这是蓝图 XCTestCase 子类的一些示例代码,但我不必实际实例化此类:

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

2 回答 2

1

这些XCTestCase类的实例化方式与所有其他类相同。

只是它们是在 a 中创建的separate process,一切都由 XCTest 框架管理,要么您运行所有测试并实例化与测试目标相关的所有类,要么您选择单独的测试并实例化单独的类。

您可以在此处调查 XCTest 源代码:https ://github.com/apple/swift-corelibs-xctest

于 2017-04-04T14:01:27.093 回答
1

当你运行你的应用程序时,你的代码不负责创建应用程序委托:UIKit 框架承担了这个责任。

同样,当您运行测试时,测试运行器负责实例化您的测试用例。它通过在所有已加载类的列表中搜索属于一种 XCTestCase 的类来发现它们。然后它向每个类询问其测试调用。然后它可以为这些测试方法创建测试用例实例并运行测试。

其工作原理的关键是 Objective-C 运行时提供的丰富元数据以及它提供的用于查询和操作该信息的元编程接口。

于 2017-05-14T01:35:22.690 回答