Article
Adventures in iOS Dev Automation
December 12, 2018
At Livefront, we love unit testing . Part of that is setting up mocks — fake objects you use with dependency injection to make sure the right methods are being called.
Android has the Mockito framework where you can trivially make mocks and dictate return values. We don’t have anything that slick in Swift due to its reflection restrictions. There’s Cuckoo and SwiftyMocky, but I found them a bit onerous. They both generate helpful code (and I’m all for generating code ), but way too much. I only want to generate code I’m going to use.
I’m going to show you how to automatically generate a default implementation and mock of a Swift protocol. Computers make us more efficient. Let’s use the computer to make our computer-use more efficient.
Sourcery — generating Swift
Sourcery is a command line tool that wraps around Stencil (a Swift template language). It also parses your file for types and adds helpful tags and filters .
Here’s what my template looks like to generate a default implementation and mock for the protocols Sourcery finds:
It’s pretty simple. All it does is iterate through the methods and calls the methodSig
macro to write them out properly. You know when Xcode notices you haven’t implemented a protocol correctly and kindly offers to throw in some stubs for you? This is about the same. If you want a more advanced mock, check out Sourcery’s AutoMockable .
Apple’s Automator
To run Sourcery, you need to execute the following command:
sourcery --sources ~/Path/To/Protocol.swift --templates ~/Path/To/Template.stencil --output ~/Output/Folder
I certainly don’t want to be typing that out every time, so at a minimum we’re throwing that in an alias. But we can do even better. Instead of having a terminal window opened up in our project’s directory all the time, we can wrap a bash script using Automator and make it accessible from the dock.
Automator comes with your Mac and is pretty simple to use. Create a new automation and add an ‘Run Shell Script’ step. It should look something like:
Save it as an app and move it to your dock! When you drag your Swift file onto it, the script will receive the file path as the first argument.
Here’s what the final workflow looks like:
This is not a generalized solution. It’s a response to a tedious task I noticed popping up regularly. I like to think of it as refactoring my work day. Am I repeating myself? Can I extract these tasks and automate them?
These computer machines are powerful. Automation can save you time and reduce the opportunity for human error.
Thanks to Keehun Nam for the inspiration!
Sean is trying to get the computer to do what he wants at Livefront .-
Sean Berry
Software Engineer