iOS XCTest framework - Unit Testing Adding test methods

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!


According to Apple:

Test Methods

A test method is an instance method of a test class that begins with the prefix test, takes no parameters, and returns void, for example, (void)testColorIsRed(). A test method exercises code in your project and, if that code does not produce the expected result, reports failures using a set of assertion APIs. For example, a function’s return value might be compared against an expected value or your test might assert that improper use of a method in one of your classes throws an exception.

So we add a test method using "test" as the prefix of the method, like:


func testSomething() {



- (void)testSomething {


To actually test the results, we use XCTAssert() method, which takes a boolean expression, and if true, marks the test as succeeded, else it will mark it as failed.

Let's say we have a method in View Controller class called sum() which calculates sum of two numbers. To test it, we use this method:


func testSum(){
    let result = viewController.sum(4, and: 5)
    XCTAssertEqual(result, 9)


- (void)testSum {
    int result = [viewController sum:4 and:5];
    XCTAssertEqual(result, 9);


By default, you can't access label, text box or other UI items of the View Controller class from test class if they are first made in Storyboard file. This is because they are initialized in loadView() method of the View Controller class, and this will not be called when testing. The best way to call loadView() and all other required methods is accessing the view property of our viewController property. You should add this line before testing UI elements:


Got any iOS Question?