11

自 Xcode 10.1(可能是 10)以来,当我创建单元测试文件时,我没有调用 super.tearDown() 和 super.setUp() 。

我在发行说明中没有看到这样的变化。

在文档中https://developer.apple.com/documentation/xctest/xctestcase/understanding_setup_and_teardown_for_test_methods仍然在这里。

所以我的问题是我还应该写 super.tearDown() 和 super.setUp() 吗?

class SomethingTests: XCTestCase {  

    override func 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.  
    }  

    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

1 回答 1

24

对于 XCTestCase 的直接子类,不调用super.setUp(). 那是因为setUpandtearDown是在顶层具有空实现的模板方法。

尽管行为没有变化,但省略对 的调用super意味着如果您创建具有多个级别的测试层次结构,则必须将它们添加回来。

你什么时候会拥有超过一个级别?有两种情况:

  • 当您想为不同的场景重用相同的测试时。
  • 当您将 XCTestCase 子类化以制作自定义助手时。

这些不会每天都发生。但它们确实发生了。决定“我在这里需要它,但我在那里不需要它”是危险的。所以我会一直打电话super

于 2018-11-24T06:13:19.933 回答