Skip to content

Instantly share code, notes, and snippets.

@ricardopereira
Forked from marinbenc/DataService.swift
Created January 4, 2017 16:26
Show Gist options
  • Save ricardopereira/818da90a88b0f855de0cdbe74c2b4ff3 to your computer and use it in GitHub Desktop.
Save ricardopereira/818da90a88b0f855de0cdbe74c2b4ff3 to your computer and use it in GitHub Desktop.
Automatically create simple mocks for protocols in Swift
{% for type in types.protocols.implementing.AutoMockable %}
{% if not type.name == "AutoMockable" %}
class {{ type.name }}Mock: {{ type.name }} {
{% for method in type.allMethods %}
var {{ method.shortName }}Called = false
func {{ method.shortName }}({% for param in method.parameters %}{{ param.argumentLabel }}{% if not param.argumentLabel == param.name %} {{ param.name }}{% endif %}: {{param.typeName }}{% if not forloop.last%}, {% endif %}{% endfor %}) {
{{ method.shortName }}Called = true
}
{% endfor %}
}
{% endif %}
{% endfor %}
import Foundation
/// Protocols confoming to this protocol will have a mock generated for them.
protocol AutoMockable {}
protocol DataServiceProtocol: AutoMockable {
func fetchResource(fromURL url: URL, onComplete: (Result)-> Void)
}
class DataService: DataServiceProtocol {
func fetchResource(fromURL url: URL, onComplete: (Result)-> Void) {
//Real implementation
//Will get replaced in the generated file
}
}
// Generated using Sourcery 0.5.0 — https://github.com/krzysztofzablocki/Sourcery
// DO NOT EDIT
class DataServiceProtocolMock: DataServiceProtocol {
var fetchResourceCalled = false
func fetchResource(fromURL url: URL, onComplete: (Result)-> Void) {
fetchResourceCalled = true
}
}

Automatically generates a mock class implementing a specific protocol. For each protocol method, the mock will provide a methodNameCalled boolean. Files:

  • DataService.swift - sample file
  • lens.stencil - sourcery template
  • DataServiceMock.swift - sample mock generated

You will need sourcery template for this to work.

Suggestions and improvements are welcome!

Inspired by Filip Zawada.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment