I am setting up unit testing for my Swift project and am having trouble testing a class function that involves updating IBOutlets.
I have a function, validateUrl, which expects a string to be passed, then validates it. If it is valid, it enables a UIButton, if it is invalid, it disables a UIButton. When I run a test that calls this function, the app crashes on the line of code that enables or disables the UIButton. The storyboard and controllers both has the proper Test target set.
This line of code:
self.submitButton.enabled = true// Enable Submit Button
Spits out this error:
fatal error: unexpectedly found nil while unwrapping an Optional value
Swift code is associated with graphical interface elements through the use of outlets and actions. An IB Outlet (short for Interface Builder outlet) is a graphical component that your code links to. An IB action is the reverse: It is a method in your code that a graphical component links to.
Writing Unit Test Cases in Swift With an ExampleUnit test cases run with the testing target. Always check if you have a unit test target or not, if not, then add it. Then under this target, you need to create a new test case file. You will use this new file for writing test cases.
Generally speaking, an Xcode Unit Test exercises and evaluates your Swift code, but does not inspect the impact is has on the User Interface, while an Xcode UI Test evaluates the UI behavior in response to actions, but does not inspect your code. As always, these are generalized statements that have exceptions.
What is unit testing? Unit tests are automated tests that run and validate a piece of code (known as the “unit”) to make sure it behaves as intended and meets its design. Unit tests have their own target in Xcode and are written using the XCTest framework.
Try this code to initialize the IbOutlets of your view controller:
let yourStoryboard = UIStoryboard(name: "Your_storyboard", bundle: nil)
yourViewController = yourStoryboard.instantiateViewController(withIdentifier: "YourViewController") as! YourViewController
yourViewController.loadView() // This line is the key
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