Introduction to Unit Test in iOS
Writing unit test cases for functionality is part of test driven development.
It’s surprising how developers and team decide not to write unit test cases and many time reason behind it is they don’t want to waste time or they have deadlines to meet. On contrary when testing team tests apps and found many bugs and it takes 1–3 days on average to debug, analysis, find, and fix those bugs if code base is very big and modules are tightly coupled. Instead if developer had wrote test cases for his/her logic, 40–60 % of bugs could have been avoided and overall software lifecycle could have been reduced.
Follow these principles for Unit test cases:
- RED — It must fail for some test cases. It would be useless to write test cases for scenarios which never fails. So, before writing test case think of use cases when and how it can be failed. It may be possible some new developer in your team changes common constant value and you are also using that constant, in this case if you had wrote test cases for your function, you can see red and rectify the mistakes and avoid bugs.
- GREEN — It should not happen that it doesnot pass for any test cases. like you are checking if 1 is equal to 2. This will never pass. These kind of test should be removed from your code.
- REFACTOR — You should be able to refactor the unit test case code and remove duplicate and redundant cases.
Steps to include test case for your class.
- Include test case file let say LearnUnitTestTests.swift

- Import @testable projectName ex: @testable import LearnUnitTest — This is require so that all modules and code of project could be access from testcase file.
- Your function name in UnitTest file should have prefix test.
See below pictures for more detail.
First snap is ViewController which have getFibonaciSumOddNumber function which calculate sum of fibonaci sequence of n.
Second snap illustrates success case.


Now, After 1 month suppose some new guy refactor your code and by mistake he changes f[0] = 0 to 1, and sometimes if function is big and some bugs come and developers are doing hit and trials by changing values. so that particular bug is fixed but it can happen that your test cases are not passed.
See below 2 snaps for failure cases:


You will get XCTAssertEqual failed: (“11”) is not equal to (“7”). i.e sum of fibonaci sequence of 4 should be 7 but not 11.
I hope after reading, you undestand power and magic of unit test cases for iOS app developer.
