Skip to content

Why you should hand make your Swift mocks

You have a couple of options when it comes to mocking in Swift. You can use a mocking framework, or you can hand make your mocks.

Why you shouldn’t use a mocking framework

It couples your tests to a third party framework. Your tests are arguably more important than your production code.

It’s more complex. Do you really need that complexity? 99% of tests that use mocks are just checking if a specific method was invoked, or if a property or the correct parameter is set.

Stuff goes wrong. The last thing you want to have to do is debug your test because your mock is behaving strangely. It doesn’t even have to be a bug in the framework; it could just not behave as you expect.

Too many mocks are bad for your tests. If you rely on too many mocks then your tests will be testing the interactions between objects rather than what the code actually does which means you will be coupling your tests to your production code. And this makes it harder to refactor your production code which is what unit testing is all about.

Why you should hand make your mocks

Here’s an example of a hand made mock:

It’s simple. It is good enough for 99% of test cases and it’s easy to write and understand.

It’s customisable. You can subclass it for those 1% of cases where this doesn’t fulfil your needs. For example an integration test may need to call a closure on a different thread or something.

It’s transparent. There’s no wizardry here.

It’s free from dependencies. Your test suite will still work if a framework loses support.

But it comes with a disadvantage: they are a pain to write and maintain.

Kill me now

The overhead isn’t huge but it can be enough to stop your flow and this is a problem I have encountered in many different teams.

But there is a solution.

I’ve got an app for that

It’s not a runtime or buildtime dependency. It’s just an automation tool that saves you some time.

It doesn’t add complexity. It just creates a hand made mock for you.

It’s not a command line tool. It works right in your IDE with a click of the button.

It takes away the initial writing and maintenance of your mocks; that’s all.

Here are the Xcode and AppCode plugins in action.

The Xcode plugin is a Source Editor Extension:

The AppCode plugin:

AppCode plugin generates Swift mock

Published iniOS

Be First to Comment

Leave a Reply