Improve Your Tests With Fixtures

Eduardo Sanches Bocato
1 min readDec 2, 2020

Introduction

Mocking values for a test can be a very demanding and sluggish.
And sometimes we end up with a big test code with bad readability, that is even harder to understand because of the amount of setup needed for our mock objects.
To improve this kind of situations and avoid these problems, we can rely on very a very simple technique: the implementation of Fixtures. They are basically custom initializers to simplify the construction of objects needed for our tests.

Case Study and Examples

Let’s suppose that the User struct has even more properties, but your tests are interested only in the nickname property. You could use a fixture to make it clear what is being tested, while also simplifying your test…

The fixture for User, could be this:

After creating the fixture, our test can be refactored to:

Conclusion

For more details on this technique, consider reading this article. It was a great source make me understand how valuable this simple technique can be on a daily basis and how beneficial it is for your test suite.

--

--

Eduardo Sanches Bocato

iOS Engineer, AI enthusiast, Crossfit/Gymnastics. Currently working as iOS Lead @adidas