XCTestCase optional instance variable

▼魔方 西西 提交于 2021-02-07 08:09:56

问题


Why is my optional instance variable nil when I infact set it to non-nil?

Code:

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()succeeds while test_B_fooIsNotNil() fails


回答1:


From Flow of Test Execution (emphasis added):

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.

In your case, test_B_fooIsNotNil() is executed on a fresh instance, for which the foo property is nil.

Common setup code can be put into the setUp() class method or setUp() instance method, see Understanding Setup and Teardown for Test Methods



来源:https://stackoverflow.com/questions/48562711/xctestcase-optional-instance-variable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!