How to write unit tests in Clean-Swift

Jeroen de Vrind
Short Swift Stories
10 min readFeb 15, 2019

--

Photo by Helloquence on Unsplash

In part 1 I explain how you can improve the architecture of your app to make it better unit testable.

Writing tests should be as much fun as writing code, right? But why isn’t it? That’s what I asked myself and I noticed that every time I tried to write some tests, I didn’t know where to begin or what to test. And if I had an idea, it turned out I couldn’t test it or I didn’t know how to test it.

After a while I started to realise that if you have a clear structure of your code, you get to know where to put what in your code and it’s becoming clear what to test. In part 1 you can read how to structure your code according to the Clean Swift pattern. In this part you can read what you can test and how you can test it.

In general good tests are flexible but not fragile, which means that if you change one line of code, it should not break lots of tests. Your tests should be extensive, cover all edge cases and run fast. So you can run them often and get feedback as quick as possible.

Structure of a unit test

In a test you can distinguish a subject that you’re going to test, inputs and outputs. It’s good to identify these three different parts because they help you to figure out what you need to do with them. For example you will never stubyour test subject, but a…

--

--

Jeroen de Vrind
Short Swift Stories

iOS Engineer at ABN Amro bank. Author of How to develop accessible iOS apps.