SkillAgentSearch skills...

Mocker

Mock Alamofire and URLSession requests without touching your code implementation

Install / Use

/learn @WeTransfer/Mocker
About this skill

Quality Score

0/100

Supported Platforms

Universal

README

<p align="center"> <img width="900px" src="Assets/artwork.jpg"> </p> <p align="center"> <img src="https://api.travis-ci.org/WeTransfer/Mocker.svg?branch=master"/> <img src="https://img.shields.io/cocoapods/v/Mocker.svg?style=flat"/> <img src="https://img.shields.io/cocoapods/l/Mocker.svg?style=flat"/> <img src="https://img.shields.io/cocoapods/p/Mocker.svg?style=flat"/> <img src="https://img.shields.io/badge/language-swift4.2-f48041.svg?style=flat"/> <img src="https://img.shields.io/badge/carthage-compatible-4BC51D.svg?style=flat"/> <img src="https://img.shields.io/badge/spm-compatible-4BC51D.svg?style=flat"/> <img src="https://img.shields.io/badge/License-MIT-yellow.svg?style=flat"/> </p>

Mocker is a library written in Swift which makes it possible to mock data requests using a custom URLProtocol.

Features

Run all your data request unit tests offline 🎉

  • [x] Create mocked data requests based on an URL
  • [x] Create mocked data requests based on a file extension
  • [x] Works with URLSession using a custom protocol class
  • [x] Supports popular frameworks like Alamofire

Usage

Unit tests are written for the Mocker which can help you to see how it works.

Activating the Mocker

The mocker will automatically be activated for the default URL loading system like URLSession.shared after you've registered your first Mock.

Custom URLSessions

To make it work with your custom URLSession, the MockingURLProtocol needs to be registered:

let configuration = URLSessionConfiguration.default
configuration.protocolClasses = [MockingURLProtocol.self]
let urlSession = URLSession(configuration: configuration)
Alamofire

Quite similar like registering on a custom URLSession.

let configuration = URLSessionConfiguration.af.default
configuration.protocolClasses = [MockingURLProtocol.self]
let sessionManager = Alamofire.Session(configuration: configuration)

Register Mocks

Create your mocked data

It'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:

public final class MockedData {
    public static let botAvatarImageResponseHead: Data = try! Data(contentsOf: Bundle(for: MockedData.self).url(forResource: "Resources/Responses/bot-avatar-image-head", withExtension: "data")!)
    public static let botAvatarImageFileUrl: URL = Bundle(for: MockedData.self).url(forResource: "wetransfer_bot_avater", withExtension: "png")!
    public static let exampleJSON: URL = Bundle(for: MockedData.self).url(forResource: "Resources/JSON Files/example", withExtension: "json")!
}
JSON Requests
let originalURL = URL(string: "https://www.wetransfer.com/example.json")!
    
let mock = Mock(url: originalURL, contentType: .json, statusCode: 200, data: [
    .get : try! Data(contentsOf: MockedData.exampleJSON) // Data containing the JSON response
])
mock.register()

URLSession.shared.dataTask(with: originalURL) { (data, response, error) in
    guard let data = data, let jsonDictionary = (try? JSONSerialization.jsonObject(with: data, options: [])) as? [String: Any] else {
        return
    }
    
    // jsonDictionary contains your JSON sample file data
    // ..
    
}.resume()
Empty Responses
let originalURL = URL(string: "https://www.wetransfer.com/api/foobar")!
var request = URLRequest(url: originalURL)
request.httpMethod = "PUT"
    
let mock = Mock(request: request, statusCode: 204)
mock.register()

URLSession.shared.dataTask(with: originalURL) { (data, response, error) in
    // ....
}.resume()
Ignoring the query

Some URLs like authentication URLs contain timestamps or UUIDs in the query. To mock these you can ignore the Query for a certain URL:

/// Would transform to "https://www.example.com/api/authentication" for example.
let originalURL = URL(string: "https://www.example.com/api/authentication?oauth_timestamp=151817037")!
    
let mock = Mock(url: originalURL, ignoreQuery: true, contentType: .json, statusCode: 200, data: [
    .get : try! Data(contentsOf: MockedData.exampleJSON) // Data containing the JSON response
])
mock.register()

URLSession.shared.dataTask(with: originalURL) { (data, response, error) in
    guard let data = data, let jsonDictionary = (try? JSONSerialization.jsonObject(with: data, options: [])) as? [String: Any] else {
        return
    }
    
    // jsonDictionary contains your JSON sample file data
    // ..
    
}.resume()
File extensions
let imageURL = URL(string: "https://www.wetransfer.com/sample-image.png")!

Mock(fileExtensions: "png", contentType: .imagePNG, statusCode: 200, data: [
    .get: try! Data(contentsOf: MockedData.botAvatarImageFileUrl)
]).register()

URLSession.shared.dataTask(with: imageURL) { (data, response, error) in
    let botAvatarImage: UIImage = UIImage(data: data!)! // This is the image from your resources.
}.resume()
Custom HEAD and GET response
let exampleURL = URL(string: "https://www.wetransfer.com/api/endpoint")!

Mock(url: exampleURL, contentType: .json, statusCode: 200, data: [
    .head: try! Data(contentsOf: MockedData.headResponse),
    .get: try! Data(contentsOf: MockedData.exampleJSON)
]).register()

URLSession.shared.dataTask(with: exampleURL) { (data, response, error) in
	// data is your mocked data
}.resume()
Custom DataType

In 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.

let xmlURL = URL(string: "https://www.wetransfer.com/sample-xml.xml")!

Mock(fileExtensions: "png", contentType: .init(name: "xml", headerValue: "text/xml"), statusCode: 200, data: [
    .get: try! Data(contentsOf: MockedData.sampleXML)
]).register()

URLSession.shared.dataTask(with: xmlURL) { (data, response, error) in
    let sampleXML: Data = data // This is the xml from your resources.
}.resume(
Delayed responses

Sometimes 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:

let exampleURL = URL(string: "https://www.wetransfer.com/api/endpoint")!

var mock = Mock(url: exampleURL, contentType: .json, statusCode: 200, data: [
    .head: try! Data(contentsOf: MockedData.headResponse),
    .get: try! Data(contentsOf: MockedData.exampleJSON)
])
mock.delay = DispatchTimeInterval.seconds(5)
mock.register()
Redirect responses

Sometimes 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:

Date: Tue, 10 Oct 2017 07:28:33 GMT
Location: https://wetransfer.com/redirect

By creating a mock for the short URL and the redirect URL, you can mock redirect and test this behavior:

let urlWhichRedirects: URL = URL(string: "https://we.tl/redirect")!
Mock(url: urlWhichRedirects, contentType: .html, statusCode: 200, data: [.get: try! Data(contentsOf: MockedData.redirectGET)]).register()
Mock(url: URL(string: "https://wetransfer.com/redirect")!, contentType: .json, statusCode: 200, data: [.get: try! Data(contentsOf: MockedData.exampleJSON)]).register()
Ignoring URLs

As 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:

let ignoredURL = URL(string: "https://www.wetransfer.com")!

// Ignore any requests that exactly match the URL
Mocker.ignore(ignoredURL)

// Ignore any requests that match the URL, with any query parameters
// e.g. https://www.wetransfer.com?foo=bar would be ignored
Mocker.ignore(ignoredURL, matchType: .ignoreQuery)

// Ignore any requests that begin with the URL
// e.g. https://www.wetransfer.com/api/v1 would be ignored
Mocker.ignore(ignoredURL, matchType: .prefix)

However, if you need the Mocker to catch only mocked URLs and ignore every other URL, you can set the mode attribute to .optin.

Mocker.mode = .optin

If you want to set the original mode back, you have just to set it to .optout.

Mocker.mode = .optout
Mock errors

You can request a Mock to return an error, allowing testing of error handling.

Mock(url: originalURL, contentType: .json, statusCode: 500, data: [.get: Data()],
     requestError: TestExampleError.example).register()

URLSession.shared.dataTask(with: originalURL) { (data, urlresponse, err) in
    XCTAssertNil(data)
    XCTAssertNil(urlresponse)
    XCTAssertNotNil(err)
    if let err = err {
        // there's not a particularly elegant way to verify an instance
        // of an error, but this is a convenient workaround for testing
        // purposes
        XCTAssertEqual("example", String(describing: err))
    }

    expectation.fulfill()
}.resume()
Mock callbacks

You can register on Mock callbacks to make testing easier.

View on GitHub
GitHub Stars1.2k
CategoryDevelopment
Updated7d ago
Forks97

Languages

Swift

Security Score

100/100

Audited on Mar 17, 2026

No findings