{"id":13466121,"url":"https://github.com/WeTransfer/Mocker","last_synced_at":"2025-03-25T21:31:19.652Z","repository":{"id":39156098,"uuid":"97627989","full_name":"WeTransfer/Mocker","owner":"WeTransfer","description":"Mock Alamofire and URLSession requests without touching your code implementation","archived":false,"fork":false,"pushed_at":"2024-09-10T17:46:44.000Z","size":1095,"stargazers_count":1123,"open_issues_count":3,"forks_count":96,"subscribers_count":19,"default_branch":"master","last_synced_at":"2024-10-29T15:40:01.213Z","etag":null,"topics":["wt-branch-protection-exempt","wt-branch-protection-two-approvals"],"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/WeTransfer.png","metadata":{"files":{"readme":"README.md","changelog":"Changelog.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":".github/CODEOWNERS","security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2017-07-18T17:55:24.000Z","updated_at":"2024-10-27T12:14:44.000Z","dependencies_parsed_at":"2024-03-18T17:04:28.768Z","dependency_job_id":"cc8dfa16-8671-469f-a9ff-8779c4f3ae5d","html_url":"https://github.com/WeTransfer/Mocker","commit_stats":{"total_commits":200,"total_committers":38,"mean_commits":"5.2631578947368425","dds":"0.45999999999999996","last_synced_commit":"8bbd037cb9d176d79613026561c8ba034bd35662"},"previous_names":[],"tags_count":24,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/WeTransfer%2FMocker","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/WeTransfer%2FMocker/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/WeTransfer%2FMocker/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/WeTransfer%2FMocker/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/WeTransfer","download_url":"https://codeload.github.com/WeTransfer/Mocker/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":245547314,"owners_count":20633344,"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":["wt-branch-protection-exempt","wt-branch-protection-two-approvals"],"created_at":"2024-07-31T15:00:39.432Z","updated_at":"2025-03-25T21:31:19.398Z","avatar_url":"https://github.com/WeTransfer.png","language":"Swift","funding_links":[],"categories":["Libs","Testing [🔝](#readme)","Swift"],"sub_categories":["Testing"],"readme":"\u003cp align=\"center\"\u003e\n    \u003cimg width=\"900px\" src=\"Assets/artwork.jpg\"\u003e\n\u003c/p\u003e\n\n\u003cp align=\"center\"\u003e\n\u003cimg src=\"https://api.travis-ci.org/WeTransfer/Mocker.svg?branch=master\"/\u003e\n\u003cimg src=\"https://img.shields.io/cocoapods/v/Mocker.svg?style=flat\"/\u003e\n\u003cimg src=\"https://img.shields.io/cocoapods/l/Mocker.svg?style=flat\"/\u003e\n\u003cimg src=\"https://img.shields.io/cocoapods/p/Mocker.svg?style=flat\"/\u003e\n\u003cimg src=\"https://img.shields.io/badge/language-swift4.2-f48041.svg?style=flat\"/\u003e\n\u003cimg src=\"https://img.shields.io/badge/carthage-compatible-4BC51D.svg?style=flat\"/\u003e\n\u003cimg src=\"https://img.shields.io/badge/spm-compatible-4BC51D.svg?style=flat\"/\u003e\n\u003cimg src=\"https://img.shields.io/badge/License-MIT-yellow.svg?style=flat\"/\u003e\n\u003c/p\u003e\n\nMocker is a library written in Swift which makes it possible to mock data requests using a custom `URLProtocol`.\n\n- [Features](#features)\n- [Requirements](#requirements)\n- [Usage](#usage)\n    - [Activating the Mocker](#activating-the-mocker)\n\t    - [Custom URLSessions](#custom-urlsessions)\n\t    - [Alamofire](#alamofire)\n    - [Register Mocks](#register-mocks)\n\t    - [Create your mocked data](#create-your-mocked-data)\n\t    - [JSON Requests](#json-requests)\n\t    - [File extensions](#file-extensions)\n\t    - [Custom HEAD and GET response](#custom-head-and-get-response)\n\t    - [Delayed responses](#delayed-responses)\n\t    - [Redirect responses](#redirect-responses)\n\t    - [Ignoring URLs](#ignoring-urls)\n\t    - [Mock callbacks](#mock-callbacks)\n    - [Unregister Mocks](#unregister-mocks)\n\t    - [Clear all registered mocks](#clear-all-registered-mocks)\n- [Communication](#communication)\n- [Installation](#installation)\n- [Release Notes](#release-notes)\n- [License](#license)\n\n## Features\n_Run all your data request unit tests offline_ 🎉\n\n- [x] Create mocked data requests based on an URL\n- [x] Create mocked data requests based on a file extension\n- [x] Works with `URLSession` using a custom protocol class\n- [x] Supports popular frameworks like `Alamofire`\n\n## Usage\n\nUnit tests are written for the `Mocker` which can help you to see how it works.\n\n### Activating the Mocker\nThe mocker will automatically be activated for the default URL loading system like `URLSession.shared` after you've registered your first `Mock`. \n\n##### Custom URLSessions\nTo make it work with your custom `URLSession`, the `MockingURLProtocol` needs to be registered:\n\n```swift\nlet configuration = URLSessionConfiguration.default\nconfiguration.protocolClasses = [MockingURLProtocol.self]\nlet urlSession = URLSession(configuration: configuration)\n```\n\n##### Alamofire\nQuite similar like registering on a custom `URLSession`.\n\n```swift\nlet configuration = URLSessionConfiguration.af.default\nconfiguration.protocolClasses = [MockingURLProtocol.self]\nlet sessionManager = Alamofire.Session(configuration: configuration)\n```\n\n### Register Mocks\n##### Create your mocked data\nIt's recommended to create a class with all your mocked data accessible. An example of this can be found in the unit tests of this project:\n\n```swift\npublic final class MockedData {\n    public static let botAvatarImageResponseHead: Data = try! Data(contentsOf: Bundle(for: MockedData.self).url(forResource: \"Resources/Responses/bot-avatar-image-head\", withExtension: \"data\")!)\n    public static let botAvatarImageFileUrl: URL = Bundle(for: MockedData.self).url(forResource: \"wetransfer_bot_avater\", withExtension: \"png\")!\n    public static let exampleJSON: URL = Bundle(for: MockedData.self).url(forResource: \"Resources/JSON Files/example\", withExtension: \"json\")!\n}\n```\n\n##### JSON Requests\n``` swift\nlet originalURL = URL(string: \"https://www.wetransfer.com/example.json\")!\n    \nlet mock = Mock(url: originalURL, contentType: .json, statusCode: 200, data: [\n    .get : try! Data(contentsOf: MockedData.exampleJSON) // Data containing the JSON response\n])\nmock.register()\n\nURLSession.shared.dataTask(with: originalURL) { (data, response, error) in\n    guard let data = data, let jsonDictionary = (try? JSONSerialization.jsonObject(with: data, options: [])) as? [String: Any] else {\n        return\n    }\n    \n    // jsonDictionary contains your JSON sample file data\n    // ..\n    \n}.resume()\n```\n\n##### Empty Responses\n``` swift\nlet originalURL = URL(string: \"https://www.wetransfer.com/api/foobar\")!\nvar request = URLRequest(url: originalURL)\nrequest.httpMethod = \"PUT\"\n    \nlet mock = Mock(request: request, statusCode: 204)\nmock.register()\n\nURLSession.shared.dataTask(with: originalURL) { (data, response, error) in\n    // ....\n}.resume()\n```\n\n##### Ignoring the query\nSome URLs like authentication URLs contain timestamps or UUIDs in the query. To mock these you can ignore the Query for a certain URL:\n\n``` swift\n/// Would transform to \"https://www.example.com/api/authentication\" for example.\nlet originalURL = URL(string: \"https://www.example.com/api/authentication?oauth_timestamp=151817037\")!\n    \nlet mock = Mock(url: originalURL, ignoreQuery: true, contentType: .json, statusCode: 200, data: [\n    .get : try! Data(contentsOf: MockedData.exampleJSON) // Data containing the JSON response\n])\nmock.register()\n\nURLSession.shared.dataTask(with: originalURL) { (data, response, error) in\n    guard let data = data, let jsonDictionary = (try? JSONSerialization.jsonObject(with: data, options: [])) as? [String: Any] else {\n        return\n    }\n    \n    // jsonDictionary contains your JSON sample file data\n    // ..\n    \n}.resume()\n```\n\n##### File extensions\n```swift\nlet imageURL = URL(string: \"https://www.wetransfer.com/sample-image.png\")!\n\nMock(fileExtensions: \"png\", contentType: .imagePNG, statusCode: 200, data: [\n    .get: try! Data(contentsOf: MockedData.botAvatarImageFileUrl)\n]).register()\n\nURLSession.shared.dataTask(with: imageURL) { (data, response, error) in\n    let botAvatarImage: UIImage = UIImage(data: data!)! // This is the image from your resources.\n}.resume()\n```\n\n##### Custom HEAD and GET response\n```swift\nlet exampleURL = URL(string: \"https://www.wetransfer.com/api/endpoint\")!\n\nMock(url: exampleURL, contentType: .json, statusCode: 200, data: [\n    .head: try! Data(contentsOf: MockedData.headResponse),\n    .get: try! Data(contentsOf: MockedData.exampleJSON)\n]).register()\n\nURLSession.shared.dataTask(with: exampleURL) { (data, response, error) in\n\t// data is your mocked data\n}.resume()\n```\n\n##### Custom DataType\nIn addition to the already build in static `DataType` implementations it is possible to create custom ones that will be used as the value to the `Content-Type` header key. \n\n```swift\nlet xmlURL = URL(string: \"https://www.wetransfer.com/sample-xml.xml\")!\n\nMock(fileExtensions: \"png\", contentType: .init(name: \"xml\", headerValue: \"text/xml\"), statusCode: 200, data: [\n    .get: try! Data(contentsOf: MockedData.sampleXML)\n]).register()\n\nURLSession.shared.dataTask(with: xmlURL) { (data, response, error) in\n    let sampleXML: Data = data // This is the xml from your resources.\n}.resume(\n```\n\n\n##### Delayed responses\nSometimes you want to test if the cancellation of requests is working. In that case, the mocked request should not finish immediately and you need a delay. This can be added easily:\n\n```swift\nlet exampleURL = URL(string: \"https://www.wetransfer.com/api/endpoint\")!\n\nvar mock = Mock(url: exampleURL, contentType: .json, statusCode: 200, data: [\n    .head: try! Data(contentsOf: MockedData.headResponse),\n    .get: try! Data(contentsOf: MockedData.exampleJSON)\n])\nmock.delay = DispatchTimeInterval.seconds(5)\nmock.register()\n```\n\n##### Redirect responses\nSometimes you want to mock short URLs or other redirect URLs. This is possible by saving the response and mocking the redirect location, which can be found inside the response:\n\n```\nDate: Tue, 10 Oct 2017 07:28:33 GMT\nLocation: https://wetransfer.com/redirect\n```\n\nBy creating a mock for the short URL and the redirect URL, you can mock redirect and test this behavior:\n\n```swift\nlet urlWhichRedirects: URL = URL(string: \"https://we.tl/redirect\")!\nMock(url: urlWhichRedirects, contentType: .html, statusCode: 200, data: [.get: try! Data(contentsOf: MockedData.redirectGET)]).register()\nMock(url: URL(string: \"https://wetransfer.com/redirect\")!, contentType: .json, statusCode: 200, data: [.get: try! Data(contentsOf: MockedData.exampleJSON)]).register()\n```\n\n##### Ignoring URLs\nAs the Mocker catches all URLs by default when registered, you might end up with a `fatalError` thrown in cases you don't need a mocked request. In that case, you can ignore the URL:\n\n```swift\nlet ignoredURL = URL(string: \"https://www.wetransfer.com\")!\n\n// Ignore any requests that exactly match the URL\nMocker.ignore(ignoredURL)\n\n// Ignore any requests that match the URL, with any query parameters\n// e.g. https://www.wetransfer.com?foo=bar would be ignored\nMocker.ignore(ignoredURL, matchType: .ignoreQuery)\n\n// Ignore any requests that begin with the URL\n// e.g. https://www.wetransfer.com/api/v1 would be ignored\nMocker.ignore(ignoredURL, matchType: .prefix)\n```\n\nHowever, if you need the Mocker to catch only mocked URLs and ignore every other URL, you can set the `mode` attribute to `.optin`. \n\n```swift\nMocker.mode = .optin\n```\n\nIf you want to set the original mode back, you have just to set it to `.optout`.\n\n```swift\nMocker.mode = .optout\n```\n\n##### Mock errors\n\nYou can request a `Mock` to return an error, allowing testing of error handling.\n\n```swift\nMock(url: originalURL, contentType: .json, statusCode: 500, data: [.get: Data()],\n     requestError: TestExampleError.example).register()\n\nURLSession.shared.dataTask(with: originalURL) { (data, urlresponse, err) in\n    XCTAssertNil(data)\n    XCTAssertNil(urlresponse)\n    XCTAssertNotNil(err)\n    if let err = err {\n        // there's not a particularly elegant way to verify an instance\n        // of an error, but this is a convenient workaround for testing\n        // purposes\n        XCTAssertEqual(\"example\", String(describing: err))\n    }\n\n    expectation.fulfill()\n}.resume()\n```\n\n##### Mock callbacks\nYou can register on `Mock` callbacks to make testing easier.\n\n```swift\nvar mock = Mock(url: request.url!, contentType: .json, statusCode: 200, data: [.post: Data()])\nmock.onRequestHandler = OnRequestHandler(httpBodyType: [[String:String]].self, callback: { request, postBodyArguments in\n    XCTAssertEqual(request.url, mock.request.url)\n    XCTAssertEqual(expectedParameters, postBodyArguments)\n    onRequestExpectation.fulfill()\n})\nmock.completion = {\n    endpointIsCalledExpectation.fulfill()\n}\nmock.register()\n```\n\n##### Mock expectations\nInstead of setting the `completion` and `onRequest` you can also make use of expectations:\n\n```swift\nvar mock = Mock(url: url, contentType: .json, statusCode: 200, data: [.get: Data()])\nlet requestExpectation = expectationForRequestingMock(\u0026mock)\nlet completionExpectation = expectationForCompletingMock(\u0026mock)\nmock.register()\n\nURLSession.shared.dataTask(with: URLRequest(url: url)).resume()\n\nwait(for: [requestExpectation, completionExpectation], timeout: 2.0)\n```\n\n### Unregister Mocks\n##### Clear all registered mocks\nYou can clear all registered mocks:\n\n```swift\nMocker.removeAll()\n```\n\n## Communication\n\n- If you **found a bug**, open an issue.\n- If you **have a feature request**, open an issue.\n- If you **want to contribute**, submit a pull request.\n\n## Installation\n\n### Carthage\n\n[Carthage](https://github.com/Carthage/Carthage) is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks.\n\nYou can install Carthage with [Homebrew](http://brew.sh/) using the following command:\n\n```bash\n$ brew update\n$ brew install carthage\n```\n\nTo integrate Mocker into your Xcode project using Carthage, specify it in your `Cartfile`:\n\n```ogdl\ngithub \"WeTransfer/Mocker\" ~\u003e 3.0.0\n```\n\nRun `carthage update` to build the framework and drag the built `Mocker.framework` into your Xcode project.\n\n### Swift Package Manager\n\nThe [Swift Package Manager](https://swift.org/package-manager/) is a tool for managing the distribution of Swift code. It’s integrated with the Swift build system to automate the process of downloading, compiling, and linking dependencies.\n\n#### Manifest File\n\nAdd Mocker as a package to your `Package.swift` file and then specify it as a dependency of the Target in which you wish to use it.\n\n```swift\nimport PackageDescription\n\nlet package = Package(\n    name: \"MyProject\",\n    platforms: [\n       .macOS(.v10_15)\n    ],\n    dependencies: [\n        .package(url: \"https://github.com/WeTransfer/Mocker.git\", .upToNextMajor(from: \"3.0.0\"))\n    ],\n    targets: [\n        .target(\n            name: \"MyProject\",\n            dependencies: [\"Mocker\"]),\n        .testTarget(\n            name: \"MyProjectTests\",\n            dependencies: [\"MyProject\"]),\n    ]\n)\n```\n\n#### Xcode\n\nTo add Mocker as a [dependency](https://developer.apple.com/documentation/xcode/adding_package_dependencies_to_your_app) to your Xcode project, select *File \u003e Swift Packages \u003e Add Package Dependency* and enter the repository URL.\n\n#### Resolving Build Errors\nIf you get the following error: *cannot find auto-link library XCTest and XCTestSwiftSupport*, set the following property under Build Options from No to Yes.  \nENABLE_TESTING_SEARCH_PATHS to YES\n\n### Manually\n\nIf you prefer not to use any of the aforementioned dependency managers, you can integrate Mocker into your project manually.\n\n#### Embedded Framework\n\n- Open up Terminal, `cd` into your top-level project directory, and run the following command \"if\" your project is not initialized as a git repository:\n\n  ```bash\n  $ git init\n  ```\n\n- Add Mocker as a git [submodule](http://git-scm.com/docs/git-submodule) by running the following command:\n\n  ```bash\n  $ git submodule add https://github.com/WeTransfer/Mocker.git\n  ```\n\n- Open the new `Mocker ` folder, and drag the `Mocker.xcodeproj` into the Project Navigator of your application's Xcode project.\n\n    \u003e It should appear nested underneath your application's blue project icon. Whether it is above or below all the other Xcode groups does not matter.\n\n- Select the `Mocker.xcodeproj` in the Project Navigator and verify the deployment target matches that of your application target.\n- Next, select your application project in the Project Navigator (blue project icon) to navigate to the target configuration window and select the application target under the \"Targets\" heading in the sidebar.\n- In the tab bar at the top of that window, open the \"General\" panel.\n- Click on the `+` button under the \"Embedded Binaries\" section.\n- Select `Mocker.framework`.\n- And that's it!\n\n  \u003e The `Mocker.framework` is automagically added as a target dependency, linked framework and embedded framework in a copy files build phase which is all you need to build on the simulator and a device.\n\n---\n\n## Release Notes\n\nSee [CHANGELOG.md](https://github.com/WeTransfer/Mocker/blob/master/Changelog.md) for a list of changes.\n\n## License\n\nMocker is available under the MIT license. See the LICENSE file for more info.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FWeTransfer%2FMocker","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FWeTransfer%2FMocker","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FWeTransfer%2FMocker/lists"}