Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - Unit testing functions that involve IBOutlets?

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
like image 409
JimmyJammed Avatar asked Nov 04 '14 17:11

JimmyJammed


People also ask

What are Iboutlets in Swift?

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.

How does swift implement unit testing?

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.

What is difference between unit tests and UI test in Xcode?

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 in iOS Swift?

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.


1 Answers

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
like image 94
Viker Avatar answered Sep 24 '22 10:09

Viker