iOS Dialogues between Hylas and Philonous

Dialogue 1: Testing View Controllers

Idriss Juhoor
3 min readFeb 4, 2016

Hylas is an iOS Developer concerned about delivering the project

Philonous is an iOS Engineer versed in code quality and maintainability

Phil: Good morning Hylas, I didn't expect to see you this early.

Hyl: I’ve spend the whole night coding this View Controller that retrieves data from a file and displays it accordingly.

Phil: That looks fine. How about the tests.

Hyl: I'm testing what can be tested. And I leave the Q.A. team to test the interface. We both know you can’t test View Controllers easily using unit tests.

Phil: I'm afraid that I don't agree with your statement.

Let’s imagine a hypothetical world where the View Controllers are not testable.

The first mistake is to keep too much logic in the View Controller. According to your hypothesis we are heading towards unexpected behaviour in the UI.

What we need is to take the logic away from the View Controller and let the View Controller control the view and only the view.

Let me explain:

In your current implementation you have a Model, a View Controller and a View.

Hyl: This is a traditional approach. Most of the examples are written this way.

Phil: For education purpose this simplification makes sense. But in essence it is difficult to maintain and test.

Let me define 2 new entities: The Data Source and the Model View.

Hyl: I know this Model View is based on the MVVM pattern but how is that going to help us?

Phil: It delegates the task of text formatting (or other presentation) from the View Controller to a new class. Some logic is taken away from the View Controller and then it can be tested. In the case of formatting it is easy to extract, since it’s pure data processing.

Hyl: I agree with you. It's also easy to test.

Phil: I can’t agree more.

Hyl: How about the Data Source?

Phil: The Data Source will delegate the data retrieval and processing tasks from the View Controller. And again it's easy to test it as a separate unit.

Hyl: And also it's easy to defer the tasks to different threads or reuse it somewhere else.

Phil: Yes, however this is irrelevant for our thesis. The same applies to how you test it, as long as it is tested.

Hyl: I agree.

Hyl: In essence testing a View Controller is extracting what can be tested and moving it in other classes.

Phil: Not exactly. It is just common sense. Let’s step out of this hypothetical world and enter the real world. What is left in this View Controller?

Hyl: There is not much left. Only the public API.

Phil: Don’t you see how testing is easy now?

Hyl: I admit, it looks much easier to test the View Controller.

Extracting the tasks not related to the control of the view didn't test the View Controller per se but it made it easier and straightforward to test the View Controller.

Here is an example of how to implement what was discussed above.

--

--