Jimmy Jimmy - 5 months ago 9
Swift Question

How do I assert object instantiation in Swift?

So I want to write a test to assert that an instance of a class has been created. My initial response was to write a test that checks the variable receiving the class for null but someone pointed out that this will not work in Swift because of optionals and that the program will crash if I were to unwrap something containing null.

So how do I test if a class, or any object for that matter, has been created properly?

I am using Swift 2.2 in Xcode 7.

And if downvoting, please let me know what is wrong with the question or formatting.

Rob Rob
Answer

If you're talking about within the context of XCTest, if you want to test to make sure it was instantiated, you can do:

func testMyObjectInstantiation() {
    let object = MyObject(value: 42)
    XCTAssert(object != nil, "instantiation failed")
}

Or

func testMyObjectInstantiation() {
    let object = MyObject(value: 42)
    XCTAssertNotNil(object, "instantiation failed")
}
Comments