iOS Testing Tips #2 — Improving the readability of your testing code

Cristian Madrid
2 min readApr 26, 2018

--

This is the second post of a series where I write tips about testing, you can check the other one here:
iOS Testing Tips #1 — Track of failing tests in helper functions

One of the most harmful things in software development is an unreadable code. When we lose too much energy trying to understand some code, we spend less energy to see the corner cases, and this is one of the most propitious ground for bugs.

Who test the tests?

Your tests are your weapons to annihilate bugs, so it’s important that it works, but how do you know that it works?

Don’t look at the code coverage to know if something is being tested, because the code coverage only check if these lines were executed.

Even though there is no silver bullet, the more unreadable your test code is, more difficult it will be to find out if all necessary contexts is being tested.

What am I supposed to do?

There are techniques that can help you organize your testing code so that it becomes more readable.

In this post, I will start with a simple test suit, then I will advance by applying these techniques.

Test case

At this example, just try to figure out what is being tested, and how to use it.

.

Refactoring with Arrange-act-assert

In the example above, it’s kind of difficult for us to discover what is being tested, Arrange-Act-Assert can help ups with that.

This technique helps you to split what is being testing from setup and assertions.

With this technique, it becomes clearer when there are testing methods, testing more than one thing at once.

Refactoring with SUT (System Under Test)

This technique helps us to identify which class we are testing, personally, I don’t use so much.

Refactoring with setup method

The setup method runs before each test method of your test suite.

This step is important, but use wisely, your tests should be readable and easy to maintain, the overuse of setup methods, can be harmful, so you have to evaluate what is best for you.

Compare each refactor step and understand what fits better to your context.
That's all folks, thanks for reading!

--

--

Cristian Madrid

iOS developer at Globo.com, In love with coffe, quality and design patterns.