64

GitHub - WeTransfer/Mocker: A simple mocker framework for Swift

 5 years ago
source link: https://github.com/WeTransfer/Mocker
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

README.md

artwork.jpg

68747470733a2f2f6170692e7472617669732d63692e6f72672f57655472616e736665722f4d6f636b65722e7376673f6272616e63683d6d6173746572 68747470733a2f2f696d672e736869656c64732e696f2f636f636f61706f64732f762f4d6f636b65722e7376673f7374796c653d666c6174 68747470733a2f2f696d672e736869656c64732e696f2f636f636f61706f64732f6c2f4d6f636b65722e7376673f7374796c653d666c6174 68747470733a2f2f696d672e736869656c64732e696f2f636f636f61706f64732f702f4d6f636b65722e7376673f7374796c653d666c6174 68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c616e67756167652d7377696674342e302d6634383034312e7376673f7374796c653d666c6174 68747470733a2f2f696d672e736869656c64732e696f2f62616467652f43617274686167652d636f6d70617469626c652d3442433531442e7376673f7374796c653d666c6174 68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e73652d4d49542d79656c6c6f772e7376673f7374796c653d666c6174

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 ?

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

Requirements

  • Swift 3+
  • iOS 8.0+
  • Xcode 9.0+

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.default
configuration.protocolClasses = [MockingURLProtocol.self]
let sessionManager = SessionManager(configuration: configuration)

Register Mocks

Create your mocked data

It's recommend 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 = Bundle(for: MockedData.self).url(forResource: "Resources/Responses/bot-avatar-image-head", withExtension: "data")!.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 : MockedData.exampleJSON.data // 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()
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?oauth_timestamp=151817037" for example.
let originalURL = URL(string: "https://www.example.com/api/authentication")!
    
let mock = Mock(url: originalURL, ignoreQuery: true, contentType: .json, statusCode: 200, data: [
    .get : MockedData.exampleJSON.data // 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: MockedData.botAvatarImageFileUrl.data
]).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: MockedData.headResponse.data,
    .get: MockedData.exampleJSON.data
]).register()

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

Sometimes you want to test if cancellation of requests is working. In that case, the mocked request should not finished directly and you need an 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: MockedData.headResponse.data,
    .get: MockedData.exampleJSON.data
])
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 mock 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 behaviour:

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

As the Mocker catches all URLs 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: "www.wetransfer.com")!
Mocker.ignore(ignoredURL)

Communication

  • If you found a bug, open an issue.
  • If you have a feature request, open an issue.
  • If you want to contribute, submit a pull request.

Installation

CocoaPods

CocoaPods is a dependency manager for Cocoa projects. You can install it with the following command:

$ gem install cocoapods

To integrate Mocker into your Xcode project using CocoaPods, specify it in your Podfile:

source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '10.0'
use_frameworks!

target '<Your Target Name>' do
    pod 'Mocker', '~> 1.0.0'
end

Then, run the following command:

$ pod install

Carthage

Carthage is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks.

You can install Carthage with Homebrew using the following command:

$ brew update
$ brew install carthage

To integrate Mocker into your Xcode project using Carthage, specify it in your Cartfile:

github "WeTransfer/Mocker" ~> 1.00

Run carthage update to build the framework and drag the built Mocker.framework into your Xcode project.

Manually

If you prefer not to use any of the aforementioned dependency managers, you can integrate Mocker into your project manually.

Embedded Framework

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

    $ git init
  • Add Mocker as a git submodule by running the following command:

    $ git submodule add https://github.com/WeTransfer/Mocker.git
  • Open the new Mocker folder, and drag the Mocker.xcodeproj into the Project Navigator of your application's Xcode project.

    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.

  • Select the Mocker.xcodeproj in the Project Navigator and verify the deployment target matches that of your application target.

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

  • In the tab bar at the top of that window, open the "General" panel.

  • Click on the + button under the "Embedded Binaries" section.

  • Select Mocker.framework.

  • And that's it!

    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.


Release Notes

See CHANGELOG.md for a list of changes.

License

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


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK