MockSwift
MockSwift allows you to write mocks and make better tests. Because MockSwift is an open source library 100% written in Swift, it is AVAILABLE ON ALL PLATFORMS.
Features
Actually MockSwift supports:
- Stub
- [x] Protocol methods
- [x] Protocol properties
- [x] Protocol subscripts
- [ ] Class
- [ ] Struct
- [ ] Enum
- [x] Default values for types
- Verify interactions
- [x] Protocol methods
- [x] Protocol properties
- [x] Protocol subscripts
- [ ] Class
- [ ] Struct
- [ ] Enum
_ Parameter matching - [x] Predicates
- [x] Generics
CHANGELOG
You can see all changes and new features here.
Installation
Swift Package Manager
MockSwift has been designed to work with Swift Package Manager.
Usage
Quick Look
Details
Suppose that you have a UserService
protocol.
And you want to test this UserCore
class.
Make better tests
Now, with MockSwift, you can use a mocked UserService
in your tests with the @Mock
annotation.
And easly configure it to fully test UseCore
.
Given
given()
enables you to define behaviours.
example:
you can also define behaviours when you instantiate the mock.
Then
then()
enables you to verify calls.
example:
You can go further and verify order of calls
Stubs
In MockSwift, stubs are default values that are returned when no behaviours has been found.
Global Stubs
You can define a global stub for any type.
It will concern all mocks you will use in every tests.
Local Stubs
You can also define a stub localy for any type.
It will concern only the current mock.
Strategy
The default strategy is to find behaviour defined with given()
. If no behaviour is found, it will return a local stub. If no local stub is found, it will return a global stub.
You can change the order of the strategy list or remove items as you want.
Write mocks
Automatically
MockSwift provides a stencil template for sourcery. You can use the AutoMockable
annotation to generate code.
To generate code at every build, you can add a build phase before Compile Sources
.
sourcery \
--sources MyLibrary \
--templates MyLibraryTests/path/to/MockSwift.stencil \
--output MyLibraryTests/path/to/GeneratedMocks.swift \
--args module=MyLibrary
Manually
To enable MockSwift for UserService type, you have to extend Mock.
To allow behaviour definition through given()
method, you have to extend Given.
To allow call verification through then()
method, you have to extend Then.