XCTestCase 可选实例变量
XCTestCase optional instance variable
为什么我的可选实例变量是 nil,而实际上我将它设置为非 nil?
代码:
class FooTests: XCTestCase {
var foo: Int?
func test_A_setFoo() {
XCTAssertNil(foo)
foo = 1
XCTAssertNotNil(foo)
}
func test_B_fooIsNotNil() {
XCTAssertNotNil(foo)
}
}
test_A_setFoo()
成功而test_B_fooIsNotNil()
失败
来自Flow of Test Execution
(强调已添加):
For each class, testing starts by running the class setup method. For each test method, a new instance of the class is allocated and its instance setup method executed. After that it runs the test method, and after that the instance teardown method. This sequence repeats for all the test methods in the class. After the last test method teardown in the class has been run, Xcode executes the class teardown method and moves on to the next class. This sequence repeats until all the test methods in all test classes have been run.
在您的例子中,test_B_fooIsNotNil()
是在新实例上执行的,
foo
属性 是 nil
.
常用设置代码可以放入setUp()
class方法
或 setUp()
实例方法,参见
Understanding Setup and Teardown for Test Methods
为什么我的可选实例变量是 nil,而实际上我将它设置为非 nil?
代码:
class FooTests: XCTestCase {
var foo: Int?
func test_A_setFoo() {
XCTAssertNil(foo)
foo = 1
XCTAssertNotNil(foo)
}
func test_B_fooIsNotNil() {
XCTAssertNotNil(foo)
}
}
test_A_setFoo()
成功而test_B_fooIsNotNil()
失败
来自Flow of Test Execution (强调已添加):
For each class, testing starts by running the class setup method. For each test method, a new instance of the class is allocated and its instance setup method executed. After that it runs the test method, and after that the instance teardown method. This sequence repeats for all the test methods in the class. After the last test method teardown in the class has been run, Xcode executes the class teardown method and moves on to the next class. This sequence repeats until all the test methods in all test classes have been run.
在您的例子中,test_B_fooIsNotNil()
是在新实例上执行的,
foo
属性 是 nil
.
常用设置代码可以放入setUp()
class方法
或 setUp()
实例方法,参见
Understanding Setup and Teardown for Test Methods