【问题标题】:Why does XCTestCase override the setup method of XCTest?为什么 XCTestCase 会覆盖 XCTest 的 setup 方法?
【发布时间】:2017-08-23 14:25:42
【问题描述】:

我想我理解继承的概念,但显然我不理解,因为如果 XCTest 在其类中提供 setup 方法,为什么 XCTestCase 中有 setup 方法? XCTestCase 是 XCTest 的子类,但在阅读了 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.
        }
    }

}

【问题讨论】:

  • 您说的是哪种设置方法?继承自 XCTest 的那一个,您在 sn-p 中重写或继承自 XCTestCase 的类方法?
  • @dan 我在我的 sn-p 中覆盖的那个
  • @dan 当我查看 Apple 的参考资料时,它们(XCTest 和 XCTestCase)都有这些方法,但它们看起来很相似,或者至少我看不到 Apple 的实现

标签: ios swift xctest xctestcase


【解决方案1】:

XCTest 是一个基类,具有空的 setUp()tearDown() 方法。

XCTestCase 继承自 XCTest,因此它继承了相同的方法。它没有自己的实现。无论如何,它们只是什么都不做的方法。它们只是被定义以便我们可以覆盖它们。这是Template Method design pattern 的示例。

为什么要在 XCTest 中定义这些方法,或者根本没有 XCTest?测试运行程序可以使用 XCTest 的任何子类,并且对 XCTestCase 一无所知。这可能使我们能够定义除 XCTestCase 子类之外的测试套件的新定义方式,同时仍与 XCTest 框架集成。

有关 xUnit 架构的更多信息,请参阅JUnit: A Cook's Tour

【讨论】:

    【解决方案2】:

    您可以覆盖子类中的方法以向超类添加更多功能。

    您可以完全覆盖超类的实现,也可以在覆盖方法中调用super.setUp() 以在您添加到覆盖中的任何内容之前执行超类的实现。

    在测试中,XCTestCase 子类通常会覆盖 setUp() 以为该类添加通用设置操作,而超类的实现将为您的整个套件执行通用设置操作。例如,一个 XCTestCase 子类将有一个 setUp() 方法来启动应用程序,而该类的一个子类将有一个 setUp() 方法,该方法调用其超类设置,然后在该类中初始化被测区域。在单元测试中,这可能意味着创建一个对象,或者在 UI 测试中,这可能意味着导航到应用中的特定页面。

    如果您希望在测试的设置阶段发生某些事情,您需要在子类化时覆盖 XCTestCase 的 setUp(),因为它默认有一个空实现。

    XCTest 定义了setUp() 方法的原因(即使它什么都不做)是为了使XCTest 上的其他方法能够调用setUp(),例如,在XCTestCase 调用setUp()invokeTest()。这使框架的用户可以通过覆盖 setUp() 方法来指定要在每个测试开始时完成的操作,该方法不需要任何测试调用逻辑,而不必用其中的其他逻辑覆盖方法,我们会在覆盖该方法时,不一定知道并且可能无法正确实现或根本不实现。这个模型使setUp() 成为一个安全的地方,您可以完全按照自己的选择执行代码,而无需担心您是否破坏了整个测试框架。

    【讨论】:

      猜你喜欢
      • 2014-01-29
      • 2021-05-17
      • 2014-02-13
      • 2011-09-16
      • 1970-01-01
      • 2018-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多