XCTest 类 func setUp() 方法如何处理失败

问题描述

因此,Apple 有一个示例,说明应如何使用 setUp 和 TearDown 方法,如下所示:

    class SetUpAndTearDownExampleTestCase: XCTestCase {
    
    override class func setUp() { // 1.
        // This is the setUp() class method.
        // It is called before the first test method begins.
        // Set up any overall initial state here.
    }
    
    override func setUpWithError() throws { // 2.
        // This is the setUpWithError() instance method.
        // It is called before each test method begins.
        // Set up any per-test state here.
    }
    
    override func setUp() { // 3.
        // This is the setUp() instance method.
        // It is called before each test method begins.
        // Use setUpWithError() to set up any per-test state,// unless you have legacy tests using setUp().
    }
    
    func testMethod1() throws { // 4.
        // This is the first test method.
        // Your testing code goes here.
        addTeardownBlock { // 5.
            // Called when testMethod1() ends.
        }
    }
    
    func testMethod2() throws { // 6.
        // This is the second test method.
        // Your testing code goes here.
        addTeardownBlock { // 7.
            // Called when testMethod2() ends.
        }
        addTeardownBlock { // 8.
            // Called when testMethod2() ends.
        }
    }
    
    override func tearDown() { // 9.
        // This is the tearDown() instance method.
        // It is called after each test method completes.
        // Use tearDownWithError() for any per-test cleanup,// unless you have legacy tests using tearDown().
    }
    
    override func tearDownWithError() throws { // 10.
        // This is the tearDownWithError() instance method.
        // It is called after each test method completes.
        // Perform any per-test cleanup here.
    }
    
    override class func tearDown() { // 11.
        // This is the tearDown() class method.
        // It is called after all test methods complete.
        // Perform any overall cleanup here.
    }
    
}

正如您在第一种方法中看到的,override class func setUp() 整体初始状态应该被设置。我有一个简单的应用程序设置阶段。但如果这以某种方式失败。然后测试就会被忽略,就像它从未运行过一样,而不是被标记为失败。

日志是这样写的:

:0:错误:simpleUITest:无法获得匹配的快照:否 为第一个查询匹配序列找到的匹配:Descendants matching type Cell -> Elements matching predicate '"login_button" IN identifiers',给定输入 App 元素 pid:9849(无属性值 故障)测试套件“simpleUITest”在 2021-01-20 失败 10:49:42.684。执行了 0 次测试,其中 1 次失败(0 次意外) 0.000 (13.204) 秒

如何将其报告为测试失败而不是让 XCTest 忽略它?

解决方法

根据文档,您至少有两个选项可以让 setUp 的测试失败:

在每次测试开始之前,XCTest 调用 setUpWithError(),然后是 setUp()。如果状态准备可能会抛出错误,请覆盖 setUpWithError()。 XCTest 在捕获错误时标记测试失败,或在捕获 XCTSkip 时跳过。

提示 您可以在测试用例的 setUp()、setUpWithError()、tearDown() 和 tearDownWithError() 实例方法中包含测试断言。任何此类断言都将作为每个测试方法运行的一部分进行评估。

不清楚您从问题中尝试了什么。您是否有第二个选项中建议的 setUp 断言?请注意,这仅适用于非类 setUp