Unit Testing in iOS

Unit Test, small term but a huge to implement. This is what I felt when I first start implementing this.But, it is interesting to write unit test once you are habitual to write them, as it helps to know where error is and why it is.

What is UNIT TESTING?

Unit testing is a process in which small chunks of code are tested independently.In simple words, it is a method by which individual units of source code are tested to determine if they are fit for use.

A Unit test is for developers, but the point is, is it so easy to implement the unit test. So, the answer is NO, it would be difficult when you do not have the practice to write them, but, YES, if you have a habit of implementing a unit test for each and every method that you write, then it is useful and best practice to write your code bug-free.In long term projects, unit test plays a very vital role and hence saves time and money as well as save you from fear of breaking of your code. Let us see why and how to implement unit test starting from basic.

Why Unit Test?

  • Enhances code quality
  • Reusability of code
  • Faster Debugging
  • Faster Development
  • Better Design/Improves design
  • Reduce Future Cost as reduces the cost of change to any code base.
  • Regression Testing
  • Reduces bugs in a new feature as well as in old features.
  • Hence, Reduces fear of changing the code and not knowing what it breaks.

How Unit Test Can be implemented: In iOS, one of the familiar tools for a unit test is XCTEST, which is integratedto in XCODE only.

XCTEST: XCTEST can be defined as:

  • It is a framework which creates and runs unit tests.
  • Performs performance tests.
  • Performs UI tests for Xcode project.
  • Tests assert that certain conditions are satisfied during code execution.
  • Record test failures (with optional messages) if conditions are not satisfied.

Pros and cons of XCTEST: As every coin has two faces,XCTEST also has some pros and cons.

Pros:

1)Easy to learn, familiar.

2)Faster than any other framework.

3)Continuous Integration is easy

4)Used with native iOS languages.

Cons:

1)No cross platform support.

2)Restricted to Objective C or Swift

Alternatives of XCTEST: There are various alternatives for performing a unit test like:

1)Appium

2)KIF(Keep It Functional): Basically it is used for performing UI test

3)Calabash

Points to keep in mind to perform UNIT TEST in iOS:

  • Written in test files.We can add additional test files in our project.
  • Test cases starts with keyword test. Syntax is:

func testMethodName(){ }

Note: @testable import productname is important.

  • You can either run a single test case or single test file or all test cases at a time, so the choice is yours.
  • Command+U is for testing whole test cases of your project.
  • You need to import third party libraries used in a test file, if required.
  • Fileprivate or private methods cannot be tested.

Your test file will look like this :

Setup and tearDown Methods: setUp is called before each test in an XCTestCase is run, and when that test finishes running, tearDown is called.These methods are useful for creating objects common to all of the tests for a test case.

Assertions in XCTEST: Unit Test is implemented using assertions.Various assertions are as following, provided by XCODE:

1)Boolean Assertions : Test a condition that generates a true or false result.

2)Nil and Non-nil Assertions: Check whether a test condition is a nil or non-nil.

3)Equality and Inequality Assertions: Check whether two values are equal or unequal.

4)Comparable Value Assertions: Compare two values to determine whether one is larger or smaller than the other.

5)Error Assertions: Check whether a function call throws (or does not throw) an error.

Test Report Viewing and generation:

  • Enable gather code coverage in edit schemes section and build settings of target.
  • Reviewing Result: Test navigator on RHS to review result.
  • For report generation, we have to use other tools.
  • Slather is one of the most commonly used tools.

Slather…What is Slather…Why Slather?

There comes a question, why slather…why not any other tool…how to use slather…does it give correct report…why we need report generation tool…does XCODE generate a report or not…??so many questions…Here is the answer…XCODE provides us the code coverage data but not in any report format.So, SLATHER is one of the tools which helps us to get the code coverage report in a proper format, which is readable and can be used in other formats like static HTML.So, let us know what slather is:

  • Ruby tool that can convert gcc coverage data to various other formats.
  • Slather is Integrated using a terminal command.
  • Needs updated version of ruby.
  • Free tool to use.
  • Generates report in a proper format like static HTML.
  • It supports various services and formats, including Codecov, Coveralls, Travis CI Pro, TeamCity, Cobertura, static HTML as outputting a quick summary to standard output.

Note: Slather uses the code coverage data, Xcode collects when you run your test suite. Slather only parses the data generated by Xcode. It does not collect or generate the code coverage data itself.

Here are few basic commands used for slather:

Command to see the percentage in terminal: To see code coverage report and percentage in terminal only, we can use this command:

slather coverage -s — scheme YourXcodeSchemeName — show path/to/project.xcodeproj

Command to see the report in HTML format:To get the report in static html format, command used is:

slather coverage -s — scheme YourXcodeSchemeName — show — html path/to/project.xcodeproj

Command to ignore files: We can ignore some files for which we do not want slather to generate a report and give percentage like the files which have only UI elements need not to be included in UNIT testing.We can ignore more than one file at a time.So, for ignoring, the command used is:

slather coverage -s — scheme YourXcodeSchemeName — show — html — ignore path/of/file path/to/project.xcodeproj

Let us have a look on a static HTML file generated by me:

Asynchronous Testing:

  • Using Asynchronous testing, tests can wait for a specified length of time for certain conditions to be satisfied.
  • Asynchronous testing can be implemented using expectations.
  • Notify test framework when the asynchronous code completes execution by making expectation as complete.
  • Steps:
  1. Create an expectation.
  2. Perform your asynchronous call.
  3. Inside your call, when it’s successful, fulfill the expectation.
  4. Outside your asynchronous call, wait for the expectation to finish.
  5. If the expectation does not finish handle the error.

Disadvantages of Unit Testing:

As I already said every coin has two faces, so, Unit testing also has some disadvantages, which are as follows:

  • It’s difficult to write good unit tests.
  • The whole process may take a lot of time.
  • Not all errors can be detected since every module is tested separately and later different integration bugs may appear.

Conclusion: Unit Testing is beneficial for all the developers to assure that their code is fit and ready to use.In long term, unit testing helps a lot as saves time and reduces cost too.

So folks, start writing a unit test for your code and give your suggestions and feedback to my writing as well.