Swift unit test - unexpectedly found nil while unwrapping an Optional value

2.2k Views Asked by At

I am trying to write a unit test which is resulting in this error

fatal error: unexpectedly found nil while unwrapping an Optional value

When I run my tests normally (Command-U) then it fails on this line in my ViewController (outside of my tests)

songTitleTextField.placeholder = "Enter your song title here..."

I'm not even trying to test this line which is whats confusing me!

When I build and run the app normally there is no issue.

Any ideas?

2

There are 2 best solutions below

1
On BEST ANSWER

Guessing here.

You say that songTitleTextField.placeholder = "Enter your song title here..." is in your viewDidLoad method, which is called from your tests.

If you look at the declaration of songTitleTextField it's probably declared someting like this:

@IBOutlet weak var songTitleTextField: UITextField!

Notice the !

Normally, when you run your app, the view is initialized properly and songTitleTextField is something. But when you run your code in test mode, the songTitleTextField has not yet been initialized and created, and therefore it is nil.

The solution could be to check whether songTitleTextField != nil before you use it. Or declare it as an optional (with ?), or perhaps set the value somewhere else.

Hope I'm right :-)

0
On

When a view controller is loaded from the storyboard, all your IBOutlets (provided they're hooked up correctly), are initialized for you. When running unit tests, there is no interaction with the storyboard, so your textField will not be initialized.

To get around this issue, you can create and assign the view of view controller yourself in unit tests class by writing this: let _ = self.mockSubject.view

Here mockSubject is the viewController.