Skip to content

Never write a Swift mock again with this AppCode plugin

Until Swift supports read and write introspection we are forced to manually write our mocks. Mocks are an essential part of testing; and where we have to write mocks, we have to write monotonous and boring code. Not only do we have to write mocks, we have to maintain them. Whenever we refactor a method, we have to refactor a mock. This AppCode plugin does all the heavy lifting for you, and creates a Swift mock in one, quick action.

AppCode plugin generates Swift mock

And what happens when we refactor a method? Run the action again and your mock is regenerated.

Install Swift Mock Generator for AppCode

  • Open AppCode
  • Open AppCode → Preferences ⌘,
  • Go to Plugins
  • Click Browse repositories…
  • Search for ‘Swift Mock Generator for AppCode’
  • Click Install
  • Restart AppCode

You can find the source code on GitHub.

Features

  • Captures invocation status of a method.
  • Captures invoked method parameters.
  • Stub values for your mocks to return.
  • Automatically calls closure parameters with stubbed values.
  • Supports mocks conforming to one or or many protocols.
  • Handles overloaded method declarations.
  • Regenerate your mock in one action.
  • Supports associated types.
  • Respects public mocks and makes queries publicly available.

How to create a new Swift mock

  • Create a mock class inheriting from from protocol(s) you would like to mock.
  • With the cursor inside the class declaration, press ⌥↵ .
  • Select ‘Generate mock’.

How to recreate a Swift mock

If you change the underlying protocol its mock will need to be regenerated. To regenerate the mock, place the cursor anywhere inside the mock and select ‘Generate mock’ again.

Usage example

A protocol called Animator that we wish to mock.

An object called MyObject using an Animator that we want to test.

A Swift mock MockAnimator generated by the Swift Mock Generator for AppCode.

A Swift test class for testing MyObject.

Test if animate was invoked.

Test the correct parameter was passed to animate.

Test the number of times animate was invoked.

Test the parameters passed into each call of the animate method.

Stub a return value for the animate method.

Stub the value for the completion closure in the animate method.

Make your own AppCode plugin

If you have a problem that could be solved with a plugin there’s some great documentation here or you can follow my step by step tutorial.

Subscribe now to hear more about AppCode tips and tricks

Published inAppCodeEssential tips you didn't know that will make you ditch XcodeiOS

Be First to Comment

Leave a Reply