Gemstones — Test Cases iOS
iOS Test cases!

We are here, to clear the basics before going to write “Test Cases”.
What we are going to do in this journey..?
- Why Test Case use?
- What are the test cases?
- When to Test?
- How to add / write Test Cases?
Why
Why to write Test Cases?
- To reduce bugs 🐛🐛🐛
- To avoid bugs when adding new features
- To clearly understands expectations of certain features, what are conditions and what are corner cases
- To refactor(restructure) large chunk of code
What
What to Test?
- Core functionality (Model classes, methods and their interaction with controller)
- Most common UI workflows
- Boundary conditions
- Bug fixes
What are the Test Cases?
Two types of Test Cases:
- Unit Test Cases
- UI Test Cases
Unit Test Case : A Unit Test Case tests a specific function under specific context.
- Tests a specific case in Class
- Make sure that the class works independently on its own.
A Unit Test Case tests a specific function under specific context.
UI Test Case : A UI Test Case tests a User Interface. It is also called Integration Testing.
- Tests user interaction testing
- Make sure all classes fits well together
- Tests UI Flow like navigations, actions, etc.
A UI Test Case tests a User Interface. It is also called Integration Testing.
What to test in Unit Test Cases?
- Data creation like Login, Register, etc
- API Class
- Major functionalities
What to test in UI Test Cases
- Font type and size : Use same Font Family, Font Sizes(Header Text, Body Text) in application
- Colors : Use consistent shades of colors
- Icons : Use consistent types of icons, like, if using flat icon, stay with it
- Visual inconsistency : Look and Feel should be same throughout the application
- Alerts : Use consistent style for alerts
- Required fields : Always specify required fields to enter data
- Data type errors : Always specify right type of data is given
- Field width : Always specify character limit
- Confirmation message : Show specific alerts for confirmation, like, data deleted / inserted, or user logged in / logged out
- Error messages : Should be informative
When
When to write the Test Cases?
- Unit Test Cases — Before going to implement actual business logic, have to write test cases for complete scenarios.
- UI Test Cases — After implementing UI and actual logic for this, it’s better time to write UI test cases.
How
How to add Test Cases?
Xcode supports Unit and UI testing.
There are three ways to add test cases in your project :
- If new Project -> select “Include Unit Tests” and “Include UI Tests”
- If ongoing Project, select Project in Bundle -> Click on add -> (Pop up will appear) -> Select “iOS” -> In “Test” section, select “iOS UI Testing Bundle” & “iOS Unit Testing Bundle” (Select Test Cases as per your need)
- In ongoing Project, select “Show the Test Navigator” -> click on “+” -> Add (as per your need) “New Unit Test Target” & “New UI Test Target”



Steps to write Test Cases?
1. Fail -> 2. Pass -> 3. Refactor
What is the meaning of these steps 🤔
- FAIL : Write test case first for failure.
- PASS : Then only go for pass the test case.
- REFACTOR : And last but least, try to refactor means restructure test case.
1. Given -> 2. When -> 3. Then
- GIVEN : What you already have, like, API url.
- WHEN : What you are going to do with this, like, getting response success/failure
- THEN : What after getting the expected output, like got response success/failure
Check the code snippet below for API call :
import XCTest
class UnitTestingTests: XCTestCase {
var sessionUnderTest: URLSession!
override func setUp() {
super.setUp()
sessionUnderTest = URLSession(configuration:URLSessionConfiguration.default)
}
func test_APIComplition() {//given let url = URL(string: "https://itunes.apple.com/search?media=music&entity=song&term=abba") let promise = expectation(description: "Complition handler invoked") var statusCode: Int?
var responseError: Error?//when let dataTask = sessionUnderTest.dataTask(with: url!) { (data, response, error) in statusCode = (response as? HTTPURLResponse)?.statusCode
responseError = error
promise.fulfill()
} dataTask.resume()
waitForExpectations(timeout: 5, handler: nil)//then
XCTAssertNil(responseError)
XCTAssertEqual(statusCode, 200) }
}
Code Snippet for Basic flow :
import XCTestclass BasicFlow: XCTestCase {func testHelloWorld() {//Given
var strHelloWorld: String?
XCTAssertNil(strHelloWorld)//When
strHelloWorld = "Hello world"//Then//this test will fail
//XCTAssertEqual(strHelloWorld, "Hello word")//this test will pass
XCTAssertEqual(strHelloWorld, "Hello world")
}
}
Code Snippet for Basic flow :
If you need to test basic functionality from your existing class in project, then,
Your ViewController Class :
import UIKitclass MainViewController: UIViewController { override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(true)
let tempInt = square(value: 2)
print("square --> \(tempInt)")
}
func square(value: Int) -> Int {
return value * value
}
}
Your Unit Test Case Class :
import XCTest //import your project here
@testable import UnitTestingclass BasicFlow: XCTestCase { func testSquareInt() {
let value:Int = 2
let squareVal = MainViewController().square(value: value)
XCTAssertEqual(squareVal, 4)
}
}
Done for Unit Test Cases!
Lets Go for UI Test Cases.. 🏃♀️
You have to write code in UITestCase class.
Check previously we have seen “How to add Test Cases”
import XCTestclass UnitTestingUITests: XCTestCase { override func setUp() {// Put setup code here. This method is called before the invocation of each test method in the class.// In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch()
}func test_LoginSuccess() { let validUsername = "abc"
let validPassword = "abc"
let app = XCUIApplication()
let txtUsername = app.textFields["username"]//this checks textfield is exists or not XCTAssertTrue(txtUsername.exists)
txtUsername.tap()
txtUsername.typeText(validUsername)
let txtPassword = app.textFields["password"]
XCTAssertTrue(txtPassword.exists)
txtPassword.tap()
txtPassword.typeText(validPassword)//select Simultor --> Hardware --> Keyboard --> Keep On "Toggle keyboard on" app.buttons["Login"].tap()//Invalid Login Case
app.alerts["Invalid credential"].buttons["Okay"].tap()//Valid Login Case
//app.alerts["Logged In"].buttons["Okay"].tap() }
}
In UITestCase, you have to write less code than Unit Test Case.
Because, here you can get as per your requirement.. 💃
For getting code for UI testing just do below steps.
- Check UI is ready for UI-Testing
- Generate UITestCase for UI
- Then, Click on ‘Record UI Test’
- It will launch your application, jump on required screen
- Click on UIControls, each click will generate code in xCode Test Case
- Easy Peasy 🙃
Here is one of demo output video : Automation UITestCase for Login

- Download source code here → https://github.com/RuchiraMore/iOS-Test-Case
Happy Coding..!!! 🙂