Clean Swift Architecture Test Driven Development Part 1 – View Controller

In my original post on Clean Swift iOS architecture, the CleanStore example app had only one scene and very little business logic. There wasn’t another scene to segue to.

In this post, you’ll add a new ListOrders scene to list the user’s orders. The user can tap a + button to segue to the CreateOrder scene you built earlier.

You’ll learn how to drive this new feature using Test Driven Development (TDD).

Design the UI

In an iOS app, without the user interface that the user can interact with, there’ll be no need for any business logic. When implementing a new feature using test driven development, it is a great idea to build the UI first.

Start by creating a new scene using the Clean Swift Xcode templates:

  • In the Project Navigator, under the Scenes group, create a new group named ListOrders.
  • Under this new group, create a new file and choose Clean Swift, then Scene.
  • Enter ListOrders for the New Scene Name.
  • Choose UITableViewController for Subclass of.
  • Create a new folder named ListOrders to put the new scene in. It’s nice to match the filesystem and the groups in Xcode so you don’t end up having all of your files in the project root.
  • Remember to check the CleanStoreTests target.

Next, create a new table view controller in storyboard:

  • Embed the new table view controller in a navigation controller
  • Make the navigation controller the new initial view controller in the Attributes Inspector.
  • In the Identity Inspector for the new table view controller:
    • Enter ListOrdersViewController for Class.
    • Enter ListOrdersViewController for Storyboard ID.
    • Check the Use Storyboard ID check box under Restoration ID.
  • Design the table view:
    • Give the new table view controller a title named Orders.
    • Add a new UIBarButtonItem in the right position of the navigation bar and choose Add for System Item. The button should turn into a +.
    • Choose Right Details for the table view cell style.
    • Enter OrderTableViewCell for the table view cell identifier.
  • Create a Show segue named ShowCreateOrderScene from the new bar button item to the CreateOrderViewController.

Your storyboard should now look like:

Clean Swift - Adding the ListOrders scene

Make sure both your storyboard file and scene files are checked for the CleanStoreTests Target Membership in the File Inspector. This is necessary for your tests to see your classes and instantiate a view controller from the storyboard.

Build and run the app to make sure everything is hooked up correctly. You should see the ListOrders scene as the first screen. When you tap the + button, you should see the CreateOrder scene you built before.

Create the unit tests

You can use my Clean Swift Xcode templates to generate the unit test files to save you a lot of typing. The templates generate unit tests for the view controller, interactor, presenter, and worker. All the common setup and teardown is done for you, so you can start writing your tests using test driven development immediately.

  • In the Project Navigator, under the Scenes group, create a new group named ListOrders.
  • Under this new group, create a new file and choose Clean Swift, then Unit Tests.
  • Enter ListOrders for the Scene Name.
  • Create a new folder named ListOrders to put the new unit tests in.
  • Check only the CleanStoreTests target. Unit test files should not be visible to your application test target.

Now you should see the following new unit test files in your project:

  • ListOrdersViewControllerTests.swift
  • ListOrdersInteractorTests.swift
  • ListOrdersPresenterTests.swift
  • ListOrdersWorkerTests.swift

What should you test first?

Where should you start first? View controller? Interactor? Presenter?

What should you test first when you do test driven development?

When the ListOrdersViewController is loaded and shown to the user, you want to show the orders to the user as soon as possible. So in the viewDidLoad() method, you want to ask the interactor to fetch some orders. That seems like a great place to start. After all, a mobile app is largely driven by user interaction.

So let’s write a test to make sure you invoke a hypothetical method named fetchOrders() inside viewDidLoad().

Isolate the dependencies

Let’s walk through what you are trying to accomplish using test driven development.

You want to fetch the list of orders when the view is loaded so the user can see them as soon as possible. Fetching orders is business logic. So you want to ask the interactor to fetch the orders in viewDidLoad().

Remember, you are testing the ListOrdersViewController, so you don’t really care what ListOrdersInteractor does after you ask it to fetch some orders and how it does so.

From the point of view of the ListOrdersViewController, it doesn’t even know it’s talking to an interactor. It just needs to know it’s talking to an output that conforms to the ListOrdersViewControllerOutput protocol.

Let’s isolate this component dependency by creating the ListOrdersViewControllerOutputSpy.

You’ll also want to isolate data dependency. So, add the ListOrders_FetchOrders_Request model to the ListOrdersModels.swift file. Leave it empty because you just want a list of orders for now. No search or sort criteria.

Write the test first

Next, write the testShouldFetchOrdersWhenViewIsLoaded() test.

First, you substitute the actual ListOrdersViewController output with the ListOrdersViewControllerOutputSpy you just wrote.

In order to load the view to be ready for testing, call loadView() to add the view controller’s view property to the view hierarchy of its root window.

The loadView() method is pretty simple:

Now, you simply need to assert that the fetchOrders() method was indeed invoked.

Draw the boundary

Next, hook up the fetchOrders() method in the boundary between ListOrdersViewController and ListOrdersInteractor. Add the fetchOrders() method to the ListOrdersViewControllerOutput and ListOrdersInteractorInput protocols.

For now, just add an empty implementation of fetchOrders() in ListOrdersInteractor. You just want to make sure the view controller asks its output to fetch orders. You don’t care what it does just yet. You’ll TDD that method when you write tests for ListOrdersInteractor.

The essence of test driven development is to write as little code as possible until it becomes necessary. An empty fetchOrders() method is needed to satisfy the protocol conformance check by the compiler.

Implement the logic

Back to the view controller test. Your test currently fails because you haven’t implemented the use case yet. Let’s make it pass now.

Add the fetchOrdersOnLoad() method to ListOrdersViewController and invoke it in viewDidLoad(). Inside fetchOrdersOnLoad(), invoke fetchOrders() on the output.

I prefer putting the actual task inside a private method because:

  • There are likely many tasks you want to perform in viewDidLoad() in the future. You don’t want to lump all of that in viewDidLoad().
  • The method name fetchOrdersOnLoad() gives a descriptive meaning to the actual task.

Run your test again to see it pass. Test driven development is fun, right?

You can find all the code and tests on GitHub.

Recap

Let’s recap what you’ve done so far using test driven development with Clean Swift.

  • You isolated the dependency on the ListOrdersInteractor component by creating the ListOrdersViewControllerOutputSpy.
  • You wrote the testShouldFetchOrdersWhenViewIsLoaded() test to verify orders are fetched when the view is loaded.
  • You implemented an empty fetchOrders() method in ListOrdersInteractor. This is good because it gives you a hint for what to test and implement next.
  • You finished the implementation by adding the fetchOrdersOnLoad() method and invoking it in viewDidLoad() to make the test pass.

In the next post, you’ll implement ListOrdersInteractor’s fetchOrders() method and create an OrdersWorker to handle the CRUD business.

Get the Clean Swift Xcode Templates

Subscribe below to get my Xcode templates and learn how to apply the VIP cycle to your projects, extract business and presentation logic into interactor and presenter, navigate to different scenes using multiple storyboards, and write fast, maintainable tests with confidence to make changes.

I promise I'll never send you spam. You can unsubscribe at any time.

Raymond
I've been developing in iOS since the iPhone debuted, jumped on Swift when it was announced. Writing well-tested apps with a clean architecture has been my goal.

11 Comments

  1. Great post.

    Have you updated the templates to add the unit test yet? I don’t see this as a selection from the files downloaded from gumtree.

    1. Yes, I updated the templates, but forgot to upload them to Gumroad. I just fixed that.

      If you’ve downloaded the templates before, you should already received an email about the update. If not, let me know.

  2. Ray,
    Great Post, eagerly waiting for your future posts.

    Have a question, why are you suggesting all the projects files to be included on the test target. You could use ‘@testable import CleanStore’ on the test swift file to make it visible in the test target to perform the testing.

    1. I am aware of the new @testable thing Apple introduced this year. It has something to do with the access modifiers – public, private, internal. I haven’t had time to look into it yet. But it surely looks good. Can you try that and uncheck the test target for your application files and let me know if it works?

      1. Using @testable is the preferred method now. Regardless of the access level of functions in your Swift file, ALL your functions are available to your test classes.

        Whether you agree this is right or not, it does mean you don’t have to add your files to the tests target which is more agreeable.

  3. Hi , i have been following your post to apply Clean Swift TDD, but actually i got a problem trying to isolate each kind of test. Because how i can see, is always needed a ViewController to init all the configuration after the awakeFromNib. Is there any other way to do TDD starting only at the presenter, skipping the view controller configuration … without alter all the test cycle?

    Thanks!

    1. Hi Alejandro,

      You can certainly test your presenter in isolation without instantiating your view controller.

      The following test code simply instantiates the subject in test, which is the presenter. There is no view controller involved. You can see the full source here.

      Also, since the presenter’s output is CreateOrderPresenterOutput, not CreateOrderViewController, and you can simply mock it in your tests. The view controller is again not involved.

      Therefore, testing your view controller, interactor, presenter, worker are completely isolated from one another due to the input/output protocols and the Dependency Inversion Principle.

  4. Surely a good post to get one started with TDD in Swift. However having a separate code for each part of your TDD series would greatly help instead of sharing a link for single completed project on git hub.

    1. Hi Akash,

      I understand what you mean.

      I tried to show the step-by-step solutions in the blog posts. They all go in the same project code base as it evolves. I thought about documenting each step as a separate commit. But that would cost way too much time for me.

      I recently ran a workshop to teach Clean Swift and used some pre-recorded screencasts. It went well based on the feedback. I may start making more screencasts and run other workshops in the future.

      1. Hi Raymond,

        Recently came across your tutorials love the content.

        If possible would you be able to record one of your workshops and posting it on youtube maybe, I believe this will extremely helpful in grasping some concepts.

Leave a Comment

Your email address will not be published. Required fields are marked *