Test your UI using Unit Tests
Broadly speaking, the tests we write fall into 3 different categories:
Unit Tests are the most simplistic tests one can write and, as the name suggests, test a single unit of code in isolation.
They are fast and stable, and we get to write lots of them — they serve as the foundation for the other tests. One common misconception is that unit tests are only to be written for models i.e. entities that deal with data.
At the other end, UI Tests are the ones that test everything as a whole — they check the system from the user perspective and are highly susceptible to breakage.
UI tests are expensive and slow, and are the ones that require the most ongoing maintenance to keep up with the evolving system.
We should always strive to minimise the amount of time tests take to run — by moving as much from UI tests to unit tests, we get the benefits of insulation and speed.
Here is an example of this…
Testing UI Constraints
Let’s say that we have a UITableView in a UIViewController and it should cover the entire view.
Instead of going through the UI tests and test various parts of the screen, we can create a unit test for it:
We might be tempted to simply check that the tableView’s frame is equal to the view’s frame like so:
But this will be bad for a whole range of reasons, probably the most important one, from the architectural perspective, being that we are testing the iOS internals.
We should only test our code — in this case we need to test that we’ve added the right constraints for that tableView, as shown in the Utilities panel:
Our test should not check if the tableView is “stretched” properly (the end result) but check if the view has the above constraints (and trust that the system does the right thing internally):
This simple test is way faster that any UI test and doesn’t depend on other parts of the app to load and display the View Controller (as required by UI tests).
Hope this helps. Happy Testing!
For completeness, here is the entire TasksViewControllerTests class: