Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: XCTest Class 'FirstDemoTests' has no initializers

I have the following code (trying to avoid implicit unwrapping):

class MyTests: XCTestCase {

    var viewController: ViewController

}

But I'm getting the following error:

Class 'MyTests' has no initializers

I fixed with this:

class MyTests: XCTestCase {

    var viewController: ViewController

    override init() {
        self.viewController = ViewController()
        super.init()
    }
}

Would be a issue using init() in XCTest class?
I'm using Swift 4, Xcode 9.2.

like image 295
user2924482 Avatar asked Feb 14 '18 22:02

user2924482


People also ask

Has no initializers Swift?

Every Swift developer runs into this error at some point. To resolve this error, you need to understand an important aspect of classes. Swift requires that the stored properties of a class receive an initial value during initialization.

How do you initialize a class in Swift?

An initializer is a special type of function that is used to create an object of a class or struct. In Swift, we use the init() method to create an initializer. For example, class Wall { ... // create an initializer init() { // perform initialization ... } }


1 Answers

I understand that you'd like to avoid implicitly unwrapping, but unfortunately (unless you want to go through the trouble of writing your own test runner), you don't have control over which initializer is called when the tests are run.

You could get around this by implicitly unwrapping, as you know, and setting the value of the property in setUp(), which gets called before every test, so you can be sure the property will not be nil during your tests. This is relatively safe.

class MyTests: XCTestCase {

    var viewController: ViewController!

    override function setUp() {
        super.setUp()
        self.viewController = ViewController()
    }
}

Alternatively, you could make the property lazy, which means that it does not have to be implicitly unwrapped. This means that the property does not have to be initialized during object initialization so you don't need to write a new initializer, but will be initialized the first time it is accessed.

class MyTests: XCTestCase {

    lazy var viewController: ViewController = {
        return ViewController()
    }()
}
like image 124
Oletha Avatar answered Nov 15 '22 21:11

Oletha