【问题标题】:How to use XCTestSuite? (Swift 3)如何使用 XCTestSuite? (斯威夫特 3)
【发布时间】:2017-05-26 05:10:38
【问题描述】:

我们有一个运行 iOS UI 测试的 Jenkins 作业,我需要能够在测试运行期间根据某些运行时信息忽略一些测试(或测试类)。根据 XCTestSuite 文档https://developer.apple.com/reference/xctest/xctestsuite,您可以通过编程方式创建自定义测试套件,但我还没有找到任何实际操作示例。那么具体是怎么做的呢?

我已经用下面的代码作为起点来玩弄这个,但还没有真正得到任何地方。当 IgnoreThisClass 在 Xcode 中运行时,其中的测试方法会运行,即使 BaseTestClass 的 setUp() 中的 testCaseCount 报告套件中的测试为 0。我是否需要重写一些 init() 方法或做其他事情?任何提示将不胜感激!

import XCTest

class BaseTestClass: XCTestCase {
    var runThis: Bool?

    override func setUp() {
        if runThis != nil {
            let suite = XCTestSuite(name: "Custom suite")

            if runThis! {
                suite.addTest(self)
            }
            print("Testcases in suite \(suite.testCaseCount)")
            // This causes an error that the suite has already started,
            // even though this call is present in Apple's example documentation.
            //suite.run()
        }
        XCUIApplication().launch()
    }

    override func tearDown() {
       super.tearDown()
    }
}

// Run this.
class RunThisClass: BaseTestClass {

    override func setUp() {
        super.runThis = true
        super.setUp()
    }

    override func tearDown() {
        super.tearDown()
    }

    func testThis() {
        print("Test class was run.")
    }
}

// Don't run this.
class IgnoreThisClass: BaseTestClass {

    override func setUp() {
        super.runThis = false
        super.setUp()
    }

    override func tearDown() {
        super.tearDown()
    }

    func testIgnoreThis() {
        print("Ignored class was run.")
    }
}

【问题讨论】:

  • 您能否举例说明何时希望动态重建您运行的测试列表?您可以简单地将特定测试移动到单独的测试包并有条件地运行它吗?
  • 例如,我们发现一些测试在运行 iOS 10 的设备上失败/表现不同,但在仍在运行 iOS 9 的设备上正常工作,而应用程序功能本身没有没变。因此,为了减少已经很长的测试运行时间,我们希望阻止失败的测试在 iOS 10 设备中运行——因为它们是误报——直到我们修复它们。我们已经有 100 多个测试并且每天都在编写更多测试,因此如果可以避免的话,我们宁愿不维护单独的测试包。

标签: ios swift3 xctest xctestcase


【解决方案1】:

要实现您想要的,您将无法从 XCTestCase 子类中初始化 XCTestSuite。这是因为为了让 XCTestCase 运行其测试(并因此进行设置),它必须已经是 XCTestSuite 的一部分 - 因此在已经初始化的测试中初始化自定义测试套件将不起作用。

Xcode 自动初始化必要的测试类,包括 XCTestSuite,因此您无法控制它的初始化时间,也无法向它发送任何自定义参数。

最好的办法是为 XCTestSuite 添加extension,并在此处添加是否运行套件中包含的测试用例的评估。

【讨论】:

  • 谢谢,所以我认为自定义套件的 suite.run() 方法一直抱怨套件已经在运行。调试器还显示默认套件已经创建。我会看看扩展 XCTestSuite。
猜你喜欢
  • 2017-03-24
  • 1970-01-01
  • 1970-01-01
  • 2017-02-15
  • 2017-04-12
  • 1970-01-01
  • 2017-07-22
  • 2014-08-31
  • 1970-01-01
相关资源
最近更新 更多