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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With