Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XCTestCase optional instance variable

Tags:

swift

xctest

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

like image 342
Peter Warbo Avatar asked Jan 29 '23 18:01

Peter Warbo


1 Answers

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

like image 152
Martin R Avatar answered Feb 01 '23 00:02

Martin R