{"id":15037462,"url":"https://github.com/pirishd/instantmock","last_synced_at":"2025-04-09T23:24:09.307Z","repository":{"id":50956145,"uuid":"90458477","full_name":"pirishd/InstantMock","owner":"pirishd","description":"Create mocks easily in Swift","archived":false,"fork":false,"pushed_at":"2021-05-26T20:04:54.000Z","size":476,"stargazers_count":90,"open_issues_count":4,"forks_count":7,"subscribers_count":7,"default_branch":"dev","last_synced_at":"2025-04-07T17:17:09.114Z","etag":null,"topics":["mock","stub","swift","swift-protocols","swift3","swift4","swift5","unit-testing"],"latest_commit_sha":null,"homepage":"","language":"Swift","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/pirishd.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2017-05-06T11:34:03.000Z","updated_at":"2025-02-16T09:03:41.000Z","dependencies_parsed_at":"2022-08-20T21:20:19.910Z","dependency_job_id":null,"html_url":"https://github.com/pirishd/InstantMock","commit_stats":null,"previous_names":[],"tags_count":30,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pirishd%2FInstantMock","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pirishd%2FInstantMock/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pirishd%2FInstantMock/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pirishd%2FInstantMock/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/pirishd","download_url":"https://codeload.github.com/pirishd/InstantMock/tar.gz/refs/heads/dev","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248127105,"owners_count":21052179,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["mock","stub","swift","swift-protocols","swift3","swift4","swift5","unit-testing"],"created_at":"2024-09-24T20:34:41.456Z","updated_at":"2025-04-09T23:24:09.288Z","avatar_url":"https://github.com/pirishd.png","language":"Swift","readme":"\u003cp align=\"center\"\u003e\n    \u003cimg src=\"https://raw.githubusercontent.com/pirishd/InstantMock/master/doc/images/logo.png\" width=\"212\" /\u003e\n\u003c/p\u003e\n\n# InstantMock\n\n## Create Mocks Easily in Swift\n\n[![Build Status](https://api.travis-ci.org/pirishd/InstantMock.svg)](https://travis-ci.org/pirishd/InstantMock/) [![codecov.io](https://codecov.io/gh/pirishd/InstantMock/branch/master/graphs/badge.svg)](https://codecov.io/gh/pirishd/InstantMock/branch/master) [![CocoaPods Plattforms](https://img.shields.io/cocoapods/p/InstantMock.svg)](https://cocoapods.org/pods/InstantMock) [![CocoaPods Version](https://img.shields.io/cocoapods/v/InstantMock.svg)](https://cocoapods.org/pods/InstantMock)\n\n*InstantMock* aims at creating mocks easily in Swift, and configuring them with expectations or stubbed implementations.\n\nFor examples, see `Example.playground`.\n\nSwift versions compatibility:\n\nSwift version | InstantMock version\n---|---\n5.0 | 2.5.X\n4.2 | 2.2.X\n4.0 | 2.0/2.1\n3.X | 1.1.X\n\n## How to Create a Mock?\n\n*InstantMock* enables to create a single mock that can be used in many tests, for a protocol or a class.\n\n### For a Protocol\n\nThe easiest way to create a mock for a protocol is to inherit from the `Mock` class.\n```Swift\n// MARK: Protocol to be mocked\nprotocol Foo {\n    func bar(arg1: String, arg2: Int) -\u003e Bool\n}\n\n// MARK: Mock class inherits from `Mock` and adopts the `Foo` protocol\nclass FooMock: Mock, Foo {\n\n    // implement `bar` of the `Foo` protocol\n    func bar(arg1: String, arg2: Int) -\u003e Bool {\n        return super.call(arg1, arg2)! // provide values to parent class\n    }\n\n}\n```\n\n### For a Class\n\nTo create a mock for a class, the mock must adopt the `MockDelegate` protocol.\n```Swift\n// MARK: Class to be mocked\nclass Foo {\n    func bar(arg1: String, arg2: Int) -\u003e Bool\n}\n\n// MARK: Mock class inherits from `Foo` and adopts the `MockDelegate` protocol\nclass FooMock: Foo, MockDelegate {\n\n    // create `Mock` delegate instance\n    private let mock = Mock()\n\n    // conform to the `MockDelegate` protocol, by providing the `Mock` instance\n    var it: Mock {\n        return mock\n    }\n\n    // implement `bar` of the `Foo` class\n    override func bar(arg1: String, arg2: Int) -\u003e Bool {\n        return mock.call(arg1, arg2)! // provide values to the delegate\n    }\n\n}\n```\n\n### Rules\n\nTo work properly, mocks must comply with a few rules regarding return values, due to Swift strong typing.\n\n#### Optional Return Value\nThe syntax is as follow:\n```Swift\nfunc returnsOptional() -\u003e Bool? {\n    return mock.call()\n}\n```\nHere, `call()` returns `nil` or `Void`.\n\n#### Non-Optional Return Value\n\nFor some methods, mocks must return non-optional values. If a return value type adopts the [MockUsable](#mockusable) protocol (which is the case for the most common types like `Bool`, `Int`…), just force unwrapping the result to `call()`, like in the following example:\n```Swift\nfunc returnsMockUsable() -\u003e Bool { // `Bool` adopts `MockUsable`\n    return mock.call()! // force unwrapping\n}\n```\nFor other types, make sure to provide a default value, like in the following example:\n```Swift\nfunc returnsCustom() -\u003e CustomType {\n    return mock.call() ?? CustomType() // return a `CustomType` default value\n}\n```\n#### Throwing\nFor catching errors on throwing methods, simply use `callThrowing()` instead of `call()`.\n\nIf a return value type adopts the [MockUsable](#mockusable) protocol (which is the case for the most common types like `Bool`, `Int`…), just force unwrapping the result to `callThrowing()`, like in the following example:\n```Swift\nfunc bazMockUsable() throws -\u003e Bool {\n    return try callThrowing()!\n}\n```\nFor other types, make sure to provide a default value, like in the following example:\n```Swift\nfunc bazCustom() throws -\u003e CustomType {\n    return try callThrowing() ?? CustomType() // return a `CustomType` default value\n}\n```\n\n#### Properties\nIt is possible to mock properties declared in a protocol, like in the following example:\n```Swift\n// define protocol with a property `prop` that has a getter and a setter\nprotocol FooProperty {\n    var prop: String { get set }\n}\n\n// mock of `FooProperty`\nclass FooPropertyMock: Mock, FooProperty {\n    var prop: String {\n        get { return super.call()! }\n        set { return super.call(newValue) }\n    }\n}\n```\n\n\n## How to Set Expectations?\n\nExpectations aim at verifying that a call is done with some arguments. They are set using a syntax like in the following example:\n```Swift\n// create mock instance\nlet mock = FooMock()\n\n// create expectation on `mock`, that is verified when `bar` is called\n// with \"hello\" for `arg1` and any value of the type of `arg2`\nmock.expect().call(\n    mock.bar(arg1: Arg.eq(\"hello\"), arg2: Arg.any())\n)\n```\n\n### Reject\nRejections are the contrary of expectations. They make sure no call is being done with some arguments. Simply use `reject()` instead of `expect()`.\n\n### Number of calls\nIn addition, expectations and rejections can be set on the number of calls:\nUse the following syntax:\n```Swift\n// create expectation on `mock`, that is verified when 2 calls are done on `bar`\n// with \"hello\" for `arg1` and any value of the type of `arg2`\nmock.expect().call(\n    mock.bar(arg1: Arg.eq(\"hello\"), arg2: Arg.any()),\n    count: 2\n)\n```\n\n### Properties\nSetting expectations on properties can be done using the following syntax:\n\n```Swift\n// create mock instance\nlet mock = FooPropertyMock()\n\n// create expectation on `mock`, that is verified when the property `prop` is called\nmock.expect().call(mock.prop)\n\n// create expectation on `mock`, that is verified when the property `prop` is set\n// with the exact value \"hello\"\nmock.expect().call(\n    mock.property.set(mock.prop, value: Arg.eq(\"hello\"))\n)\n```\n\n### Verifications\nVerifying expectations and rejections is done this way:\n```Swift\n// test fails when any of the expectations or rejections set on `mock` is not verified\nmock.verify()\n```\n\n### Reset Expectations\nExpecations can be reset this way:\n```Swift\nmock.resetExpectations()\n```\n\n## How to Stub Calls?\n\nStubs aim at performing actions when a function is called with some arguments. They are set using a syntax like in the following example:\n\n```Swift\n// create mock instance\nlet mock = FooMock()\n\n// create stubbed implementation of the `bar` method, which returns `true` when called\n// with \"hello\" for `arg1` and any value of the type of `arg2`\nmock.stub().call(\n    mock.bar(arg1: Arg.eq(\"hello\"), arg2: Arg.any())\n).andReturn(true)\n````\n\n### Return Value\nSet the return value with `andReturn(…)` on the stub instance.\n\n### Compute a Return Value\nThis is done with `andReturn(closure: { _ in return … })` on the stub instance. This enables to return different values on the same stub, depending on some conditions.\n\n### Call Another Function\nThis is done with `andDo { _ in … } ` on the stub instance.\n\n### Throw an Error\nThis is done with `andThrow(…)` on the stub instance.\n\n### Chaining\nChaining several actions on the same stub is possible, given they don't confict. For example, it is possible to return a value and call another function, like in `andReturn(true).andDo { _ in print(\"something\") }`.\n\nRules:\n* the last closure registered by `andDo` is called first\n* the last error registered by `andThrow` is thrown\n* the last return value registered by `andReturn` is returned\n* otherwise, the last return value computation method, registered by `andReturn(closure:)`, is called\n\n### Reset Stubs\nStubs can be reset this way:\n```Swift\nmock.resetStubs()\n```\n\nExample:\n```Swift\n// configure mock to return \"string\" when calling `basic` whatever provided arguments\nmock.stub().call(mock.basic(arg1: Arg.any(), arg2: Arg.any())).andReturn(\"string\")\n\n// reset the previously configured stubs\nmock.resetStubs()\n\n// calling `basic` does not return \"string\"\nlet ret = mock.basic(arg1: \"\", arg2: 2)\nXCTAssertNotEqual(ret, \"string\")\n```\n\n## Argument Matching\n\nExpectations are verified only if arguments match what is registered. Same goes for calling stubbed implementations.\n\n### Exact Value\nMatching an exact value is done with `Arg.eq(…)`.\n\nValues can be matched if they:\n- conform to the `AnyObject` protocol, which is the case for all classes implicitly, for example `Arg.eq(NSString(\"hello\"))`\n- or conform to the `MockUsable` protocol, for example `Arg.eq(42)`\n- or they are types, for example `Arg.eq(String.self)`\n- or they are tuples, limited to 5 values, for example `Arg.eq((\"a string\", 42))`\n\n### Any Value\nMatching any value can be done for types that adopt the `MockUsable` protocol, with `Arg.any()`.\n\n### Certain Condition\nMatching a value that verifies a certain condition is done with `Arg.verify({ _  in return … })`.\n\n### Closure\nMatching a closure is a special case. Use the following syntax: `Arg.closure()`.\n\n*Limitation: closures can be matched as long as they have less than 5 arguments.*\n\n## Argument Capturing\n\nArguments can also be captured for later use thanks to the `ArgumentCaptor` class.\n\nFor example:\n```Swift\n// create captor for type `String`\nlet captor = ArgumentCaptor\u003cString\u003e()\n\n// create expectation on `mock`, that is verified when `bar` is called\n// with 42 for `arg2`. All values for `arg1` are captured.\nmock.expect().call(mock.bar(arg1: captor.capture(), arg2: Arg.eq(42)))\n...\n\n// retrieve the last captured value\nlet value = captor.value\n\n// retrieve all captured values\nlet values = captor.allValues\n```\n### Capturing a Closure\n\nCapturing a closure is particularly useful for stubbing the behavior of a method with callbacks, see [this conversation](https://github.com/pirishd/InstantMock/issues/86).\n\nCapturing a closure is a special case. Use the following syntax:\n\n*Limitation: closures can be captured as long as they have less than 5 arguments.*\n\n```Swift\n// create captor for type closure `(Int) -\u003e Bool`\nlet captor = ArgumentClosureCaptor\u003c(Int) -\u003e Bool\u003e()\n...\n// retrieve the last captured closure, and call it\nlet ret = captor.value!(42)\n```\n\n## MockUsable\n`MockUsable` is a protocol that makes types easily usable in mocks.\nFor a given type, it allows to return non-optional values and to match any values.\n\nAdding `MockUsable` on an existing type is done by creating an extension that adopts the protocol. For example:\n\n\n```Swift\nextension SomeClass: MockUsable {\n\n    static var any = SomeClass() // any value\n\n    // return any value\n    public static var anyValue: MockUsable {\n        return SomeClass.any\n    }\n\n    // returns true if an object is equal to another `MockUsable` object\n    public func equal(to value: MockUsable?) -\u003e Bool {\n        guard let value = value as? SomeClass else { return false }\n        return self == value\n    }\n\n}\n```\n\nAdding `MockUsable` on an existing type that uses inheritance, should always be done on the deepest subclass.\nIndeed, adding this extension to both a parent and a subclass would create build conflicts.\n\n### Supported Types\n\nFor now, the following types are `MockUsable`:\n* Bool\n* Int, Int64\n* UInt, UInt64\n* Float\n* Double\n* String\n* Set\n* Array\n* Dictionary\n* Date\n\n## Changelog\nList of changes can be found [here](CHANGELOG.md).\n\n## Requirements\n* Xcode 10\n* iOS 9\n* osX 10.10\n\n## Installation\n### Cocoapods\n*InstantMock* is available using [CocoaPods](http://cocoapods.org), see `Podfile` example:\n```\ntarget 'Example' do\n\n    # Tests target\n    target 'ExampleTests' do\n        inherit! :search_paths\n        pod 'InstantMock'\n    end\n\nend\n```\n\n### Swift Package Manager\n\n*InstantMock* is available using the Swift Package Manager, by adding the dependency either with Xcode or by editing the `Package.swift` file:\n\n```\n.package(url: \"https://github.com/pirishd/InstantMock\", from: \"2.5.6\"),\n```\n\n## Inspiration\n\n* Argument Capture: [Mockito](http://mockito.org/)\n* Registration API: [SwiftMock](https://github.com/mflint/SwiftMock)\n\n## Author\nPatrick Irlande - pirishd@icloud.com\n\n## License\n*InstantMock* is available under the [MIT License](LICENSE).\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpirishd%2Finstantmock","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fpirishd%2Finstantmock","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpirishd%2Finstantmock/lists"}