UITesting is one of test that Xcode provides the developer to test their app specifically for the UI. Apple’s XCUITests provides simpler and easier approach to test the UI of your app. Here, I created simple app that has login view so we can test weather the logic meets valid condition. Let’s dive to the example below.

Create the Project

First, create a project that contains UITesting. To make it happend, check the UITesting text.

then, create a layout like this :

Simple login view

The layout contains two UITextFields and one UIButton. We will validate this when Login button tapped.

Next, connect the views into the your ViewController, in my case, LoginVC.swift. Here, I create simple logic that handle weather the UITextFields are empty or not.

class LoginVC: UIViewController {
// MARK: – Outlets
@IBOutlet weak var usernameTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
// MARK: – View life cycle
override func viewDidLoad() {
super.viewDidLoad()
}
// MARK: – IBAction
@IBAction func didTapLoginButton() {
guard let username = usernameTextField.text, let password = passwordTextField.text else {
print("Input cannot be empty")
return
}
print("username: \(username)")
print("password: \(password)")
}
}
view raw LoginVC.swift hosted with ❤ by GitHub

XCUITests

Open the XCUITestsDemoUITests.swift, and you will see some methods already created. In this example, I create new method called testLogin(). Inside that method, click the red circle on the bottom panel of Xcode.

The red circle on the bottom represent the record functionality. Record feature can generate your code automatically while you do your actions, like fill the textfield, tap the button, and others.

When you are finished, press the record button again and you will see some code genereated by Xcode.

Generated code by Xcode after recording.

If you want to run the test, click the diamond button near the testLogin method.

On this test, the test should fail. XCUITests is still not 100% perfect, but you can modify your code a little more to accomplish what you want. Modify your code to match below then run the test again.

Modified code to match the UI Logic Tests.

Your app should run automatically.

The simulator perform certain actions automatically.

Conclusion

XCUITests is a good and easy way to test your app’s UI. The record feature makes us less type becasue of the autogenerated code. Although sometimes the generated code is not perfect, you can still modify some code to match what you really want with the specific test behavior. This is good if you want to check your apps UI is responds correctly or not.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s