Adding test methods

suggest change

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:

Swift

func testSomething() {

}

Objective-C

- (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:

Swift

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

Objective-C

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

Note

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:

XCTAssertNotNil(viewController.view)

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents