Swiftpack.co - Package - MakeAWishFoundation/SwiftyMocky

Platform Build Status Docs License

Version Carthage compatible Mint compatible SPM compatible


Join our community on Slack! -> invitation link here

Check out guides, or full documentation

Table of contents

  1. Overview
  2. Current version
  3. Getting started:
    1. Installing SwiftyMocky CLI
    2. Integrating SwiftyMocky runtime into test target
    3. Generate mocks
  4. Usage:
    1. Marking protocols to be mocked
    2. Stubbing return values for mock methods - Given
    3. Check invocations of methods, subscripts and properties - Verify
    4. Take action when a stubbed method is called - Perform
  5. Documentation
    1. All supported Features
    2. Examples of usage
    3. Roadmap
    4. Authors
    5. License


SwiftyMocky is Lightweight, strongly typed framework for Mockito-like unit testing experience. As Swift doesn't support reflections well enough to allow building mocks in runtime, library depends on Sourcery, that scans your source code and generates Mocks Swift code for you!

The idea of SwiftyMocky is to automatically mock Swift protocols. The main features are:

  • easy syntax, utilising full power of auto-complete, which makes writing test easier and faster
  • we DO support generics
  • mock implementations generation
  • a way to specify what mock will return (given)
  • possibility to specify different return values for different attributes
  • record stubbed return values sequence
  • verify, whether a method was called on mock or not
  • check method invocations with specified attributes
  • it works with real device

Current version

We consider current version as stable. We are moving toward using the new Mockfile but the previous configuration format would be still supported, until SwiftyMocky 4.0. Library works with Swift 4.1, 4.2, 5.0, 5.1.2 and Sourcery 0.17.0.

While it is technically possible to integrate SwiftyMocky on Linux targets, there is no Mock generation feature there yet. You can use SwiftyMokcy runtime via SwiftPM though, as long as your are fine with generating mocks on mac machine.

Migration from 3.2.0 and below

The migration is not required, you can keep using SwiftyMocky as you did before. The Legacy setup is described in guides section.

Still, we would encourage to try new CLI and share a feedback. We believe it will make using and setting up SwiftyMocky way easier. If you have an existing setup, try:

> swiftymocky migrate

Getting started

To start working with SwiftyMocky you need to:

  1. Install CLI
  2. Integrate SwiftyMocky runtime library
  3. Generate Mocks and add to your test target

1. Installing SwiftyMocky CLI:

Mint 🌱:

> brew install mint
> mint install MakeAWishFoundation/SwiftyMocky

Marathon 🏃:

> marathon install MakeAWishFoundation/SwiftyMocky

2. Integrating SwiftyMocky runtime into test target:


SwiftyMocky is available through CocoaPods. To install it, simply add the following line to your Podfile:

pod "SwiftyMocky"


To install, add following to you Cartfile:

github "MakeAWishFoundation/SwiftyMocky"

Then execute carthage update

For Carthage, few additional steps are required ⚠️. For detailed install instructions, see full documentation.

Swift Package Manager:

Add SwiftyMocky to you Package.swift dependencies:

dependencies: [
    .package(url: "https://github.com/MakeAWishFoundation/SwiftyMocky", from: "3.5.0"),

Note: Examples of SwiftyMocky integration as a tool for Unit tests, as well as a Prototyping framework, are here: https://github.com/MakeAWishFoundation/SM-Integration-Tests

3. Generate mocks

Annotate your protocols that are going to be mocked, making them adopt AutoMockable protocol, or adding annotation comment above their definition in the source code.

Mocks are generated from your project root directory, based on configuration inside Mockfile.

> swiftymocky setup     # if you don't have a Mockfile yet
> swiftymocky doctor    # validate your setup
> swiftymocky generate  # generate mocks

More informations about CLI and mock generation

If you don't want to migrate to our CLI and prefer to use "raw" Sourcery, please refer to this section in documentation.


1. Marking protocols to be mocked

Create 'dummy' protocol somewhere in your project, like: protocol AutoMockable { }

Adopt it by every protocol you want to actually mock.

protocol ToBeMocked: AutoMockable {
  // ...

Alternatively, mark protocols that are meant to be mocked with sourcery annotation as following:

//sourcery: AutoMockable
protocol ToBeMocked {
  // ...

Every protocol in source directories, having this annotation, will be added to Mock.generated.swift

@objc protocols are also supported, but needs to be explicitly marked with ObjcProtocol annotation:

//sourcery: AutoMockable
//sourcery: ObjcProtocol
@objc protocol NonSwiftProtocol {
  // ...

2. Stubbing return values for mock methods - Given

All mocks has given method (accessible both as instance method or global function), with easy to use syntax, allowing to specify what should be return values for given methods (based on specified attributes).

Generating mock

All protocol methods are nicely put into Given, with matching signature. That allows to use auto-complete (just type .) to see all mocked protocol methods, and specify return value for them.

All method attributes are wrapped as Parameter enum, allowing to choose between any and value, giving great flexibility to mock behaviour. Please consider following:

Given(mock, .surname(for name: .value("Johnny"), willReturn: "Bravo"))
Given(mock, .surname(for name: .any, willReturn: "Kowalsky"))

print(mock.surname(for: "Johny"))   // Bravo
print(mock.surname(for: "Mathew"))  // Kowalsky
print(mock.surname(for: "Joanna"))  // Kowalsky

In verions 3.0 we introduced sequences and policies for better control of mock behvaiour.

Given(mock, .surname(for name: .any, willReturn: "Bravo", "Kowalsky", "Nguyen"))

print(mock.surname(for: "Johny"))   // Bravo
print(mock.surname(for: "Johny"))   // Kowalsky
print(mock.surname(for: "Johny"))   // Nguyen
print(mock.surname(for: "Johny"))   // and again Bravo
// ...

For more details please see full documentation.

3. Check invocations of methods, subscripts and properties - Verify

All mocks has verify method (accessible both as instance method or global function), with easy to use syntax, allowing to verify, whether a method was called on mock, and how many times. It also provides convenient way to specify, whether method attributes matters (and which ones).

Generating mock

All protocol methods are nicely put into Verify, with matching signature. That allows to use auto-complete (just type .) to see all mocked protocol methods, and specify which one we want to verify.

All method attributes are wrapped as Parameter enum, allowing to choose between any, value and matching, giving great flexibility to tests. Please consider following:

// inject mock to sut. Every time sut saves user data, it should trigger storage storeUser method
sut.usersStorage = mockStorage
sut.saveUser(name: "Johny", surname: "Bravo")
sut.saveUser(name: "Johny", surname: "Cage")
sut.saveUser(name: "Jon", surname: "Snow")

// check if Jon Snow was stored at least one time
Verify(mockStorage, .storeUser(name: .value("Jon"), surname: .value("Snow")))
// storeUser method should be triggered 3 times in total, regardless of attributes values
Verify(mockStorage, 3, .storeUser(name: .any, surname: .any))
// storeUser method should be triggered 2 times with name Johny
Verify(mockStorage, 2, .storeUser(name: .value("Johny"), surname: .any))
// storeUser method should be triggered at least 2 times with name longer than 3
Verify(mockStorage, .moreOrEqual(to: 2), .storeUser(name: .matching({ $0.count > 3 }}), surname: .any))

For Verify, you can use Count to specify how many times you expect something to be triggered. Count can be defined as explicit value, like 1,2,... or in more descriptive and flexible way, like .never, more(than: 1), etc.

From SwiftyMocky 3.0, it is possible to use Given and perform Verify on properties as well, with respect to whether it is get or set:

mock.name = "Danny"
mock.name = "Joanna"


// Verify getter:
Verify(mock, 1, .name)
// Verify setter:
Verify(mock, 2, .name(set: .any))
Verify(mock, 1, .name(set: .value("Danny")))
Verify(mock, .never, .name(set: .value("Bishop")))

4. Take action when a stubbed method is called - Perform

All mocks has perform method (accessible both as instance method or global function), with easy to use syntax, allowing to specify closure, that will be executed upon stubbed method being called.

It uses same parameter wrapping features as given, so you can specify different Perform cases for different attributes set.

It's very handy when working with completion block based approach.


// Perform allows to execute given closure, with all the method parameters, as soon as it is being called
Perform(mock, .methodThatTakesCompletionBlock(completion: .any, perform: { completion in


Full documentation is available here, as well as through docs directory.

Guides - Table of contents

Changelog is available here

All supported features

For list all supported features, check documentation here or guides

Examples of usage

For more examples, check out our example project, or examples section in guides.

To run the example project, clone the repo, and run pod install from the Example directory first.

To trigger mocks generation, run rake mock from root directory.


  • ☑ stubbing protocols in elegant way
  • ☑ template for generating mocks
  • ☑ example project
  • ☑ stubbing protocols with variables
  • ☑ method signature generation without name conflicts
  • ☐ cover 95% of framework codebase with unit tests
  • ☑ cover 95% of framework codebase with documentation
  • ☐ add unit tests for template
  • ☑ support for tvOS, Linux and MacOS
  • ☑ Carthage support
  • ☑ Subscripts support
  • ☑ Stub return values as sequences
  • ☑ Simple tool simplifying configuration process


  • Przemysław Wośko, wosko.przemyslaw@gmail.com
  • Andrzej Michnia, amichnia@gmail.com


SwiftyMocky is available under the MIT license. See the LICENSE file for more info.


Stars: 625

Used By

Total: 0


Version 3.4.0 - 2019-11-13 13:38:32


  • New typealias "annotation", allowing to fix common issues with generic protocols and ambigious class names
  • A "sourcery" section to mockfile, to specify additional sourcery configurations to execute during generation
  • resetMock(...) methods to reset mock internals
  • New tests suite for Xcode 11.2 (Swift 5.2)


  • deprecated clear() method on StaticMock in favour of resetMock(...)


  • Fixed Parameter ExpressibleByArrayLiteral init, by @chuckluck44 (Charley Luckhardt)
  • Fixed Xcode 11 support by @glyuck (Vladimir Lyukov)
  • Fixed typos in Readme, by @iliaskarim and @mikeakers (Mike Akers)
  • Fixed tests for swift 5.0 and linux tests

Version 3.3.4 - 2019-08-09 11:25:05


  • Fixed problem with not printable ASCI characters by @TimeDelta
  • Fixed problem with missing generic constraints by @demalex

Version 3.3.3 - 2019-06-26 09:28:54


  • Swift 5.0 issue with custom assertions not compiling

Version 3.3.2 - 2019-06-06 22:30:52


  • Fixed problems with multiple mocks being part of same target (@davidmtamas)

Version 3.3.0 - 2019-05-25 20:14:14


  • Added SwiftyMocky CLI, simplifying setup and providing doctor feature
  • Added support for Swift Package Manager (SPM)
  • New configuration file for working with multiple targets - Mockfile
  • Fixed redundant constraints for methods with stripped generics (@tarbayev)
  • Added Argument captor (@timedelta)


  • dropped Swift 4.0, SwiftyMocky now requires Swift 4.1+
  • dropped MockyCustom subspec, new subspec is Prototyping, for Carthage SwiftyPrototype

Version 3.2.0 - 2019-04-03 14:52:04


  • Fixed issues with naming, as internal name Product tend to conflict with Mocked classes
  • Swift 5.0 support, fixes for optional types casting
  • Integrated Sourcery 0.16.0, fixed issues resulting in breaking with newest Sourcery


  • No more support for Swift 3.x
  • All Given methods, that were marked as deprecated in SwiftyMocky 3.x, are now unavailable.

Version 3.1.0 - 2019-02-05 00:23:30


  • Parameter convenience constructing as .notNil, when Parameter wraps an optional type
  • Convenience Count.once as syntactic sugar for 1 for Verify
  • Proper integration with projects that already use Sourcery (@laxmorek)


  • Fixed generating mocks for methods that are throwing, and returning Self in the same time
  • Fixed associated types protocols generation, when methods generic constrained

Version 3.0.0 - 2018-10-02 19:58:44


  • Parameters handling values expressible by literals, are now also expressible by literals
  • Gracefully fail when return value is not stubbed
  • Support for subscripts
  • Stubbing policy, and support for recording sequence of return values
  • Sequencing policy, which allows to change order in which stubs are processed
  • Given for properties


  • deprecated VerifyProperty
  • deprecated setters for readonly properties
  • deprecated Given constructors not matching method signature (argument labels fix)


  • multiple generation issues, like unnamed method parameters and esaping paramters names
  • fixed issues with generics handling, when some attributes was not recognized as genric
  • fixed issues with names collisions for methods different only in argument labels

Version 2.1.0 - 2018-09-26 10:12:47

All necessary improvements to run SwiftyMocky 2.x with Xcode 10 / Swift 4.2. No breaking changes introduced.

Version 2.0.3 - 2018-05-03 10:52:21

Stabilised release for Swift 4.1. Extended support for Swift 4.1, some improvements for older Swift versions (3.3), parsing fixes.

If you experience problems with Sourcery version, try doing pod update, as Sourcery 0.13 is solving most issues.

Version 2.0.2 - 2018-04-05 13:55:49

Stable for swift 4.0.3, pre-release for swift 4.1. In most cases will require to execute get_sourcery.sh with 4.1, and as it is still work in progress, 4.1 support is not stable yet.

Version 2.0.1 - 2018-04-05 13:54:01

Stable swift 4.0.3 compatible versions

Version 1.0.2 - 2017-11-22 00:11:27

  • Fix issues for Swift 3.1
  • implement Matcher for all basic types

Version 1.0.0 - 2017-11-18 13:55:51

v0.0.1 - 2017-08-27 20:09:50

  • [x] stubbing protocols in elegant way
  • [x] base verify for mocks
  • [x] veryfying calls with different parameters
  • [x] veryfying number of calls
  • [x] build-in-assertions