Unit Testing in xcode

ref – https://x-team.com/blog/how-to-get-started-with-ios-unit-tests-in-swift/

Create a Mac OS X project

File > New > Project

Under macOS, select Command Line Tool. Name it UnitTestTutorial.

Then create a MyMath class and enter some functions for adding and multiplying.

File -> New -> File, and then under macOS, select Unit Test Case Class. If you are doing an iOS project, make sure you are under the iOS tab.
Name it MyMathTests.

You will then see a MyMathTests folder appear and see the MyMathTests.swift file.

unit-test-folder-xcode

Open the file and you’ll see something like this:

Writing test cases using XCTAssert

What we’ll do is to add code to testExample in order to run those tests.

Specifcically, XCTAssert is the starting name convention for a whole slew of test functions that you can use. Type in
XCTAssert, and a whole list of functions should appear at your disposal. You can test for truth, false, equals, Less Than, Nil, etc.

Basically, just follow the parameters and insert your functionality. There is usually a string parameter for you to put in case it fails.

output:

Test Suite ‘MyMathTests’ started at 2017-03-23 11:13:24.083
Test Case ‘-[MyMathTests.MyMathTests testExample]’ started.
/Users/rickytsao/Desktop/UnitTestTutorial/MyMathTests/MyMathTests.swift:29: error: -[MyMathTests.MyMathTests testExample] : XCTAssertLessThan failed: (“20”) is not less than (“12”) – Uh oh! Less Than testing failed
/Users/rickytsao/Desktop/UnitTestTutorial/MyMathTests/MyMathTests.swift:33: error: -[MyMathTests.MyMathTests testExample] : XCTAssertEqual failed: (“4”) is not equal to (“2”) – UH OH! FAILED!
Test Case ‘-[MyMathTests.MyMathTests testExample]’ failed (0.085 seconds).
Test Suite ‘MyMathTests’ failed at 2017-03-23 11:13:24.169.
Executed 1 test, with 2 failures (0 unexpected) in 0.085 (0.086) seconds
Test Suite ‘MyMathTests.xctest’ failed at 2017-03-23 11:13:24.169.
Executed 1 test, with 2 failures (0 unexpected) in 0.085 (0.087) seconds
Test Suite ‘Selected tests’ failed at 2017-03-23 11:13:24.170.
Executed 1 test, with 2 failures (0 unexpected) in 0.085 (0.088) seconds

Test session log:
/Users/rickytsao/Library/Developer/Xcode/DerivedData/UnitTestTutorial-aqmgqblqbwnvegfxiosuphlxvvyt/Logs/Test/54D591AF-874C-46FA-9840-4996047E7F05/Session-MyMathTests-2017-03-23_111319-FnoV9M.log