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:


Unit Testing with XCTest:
* Adding test methods

Table Of Contents
12 UIView
15 UIColor
26 UIImage
28 CALayer
30 NSDate
40 iBeacon
49 NSTimer
79 NSURL
87 AWS SDK
95 Unit Testing with XCTest
96 NSData
101 Segues
104 EventKit
105 NSBundle
106 SiriKit
111 StoreKit
117 3D Touch
119 Keychain
122 Block
141 AirDrop
144 UISlider
145 Carthage
146 HealthKit
151 plist
157 MVVM
164 UIPhoenix
166 Simulator
168 NSArray
169 OpenGL
175 Core Data
179 MyLayout
180 UIFont
189 Security
200 Codable