Skip to content

davbeck/Hippolyte

 
 

Repository files navigation

Hippolyte

Build Status codecov Version License Platform

An HTTP stubbing library written in Swift.

Requirements

  • Swift 4
  • iOS 9.3+
  • Xcode 9+

Install

Hippolyte is available on Cocoapods. Add it to your Podfile's test target:

pod 'Hippolyte'

Usage

To stub a request, first you need to create a StubRequest and StubResponse. You then register this stub with Hippolyte and tell it to intercept network requests by calling the start() method.

func testStub() {
    let url = URL(string: "http://www.apple.com")!
    var stub = StubRequest(method: .GET, url: url)
    var response = StubResponse()
    let body = "Hippolyte".data(using: .utf8)!
    response.body = body
    stub.response = response
    Hippolyte.shared.add(stubbedRequest: stub)
    Hippolyte.shared.start()

    let expectation = self.expectation(description: "Stubs network call")
    let task = URLSession.shared.dataTask(with: url) { data, _, _ in
      XCTAssertEqual(data, body)
      expectation.fulfill()
    }
    task.resume()

    wait(for: [expectation], timeout: 1)
}

It's also possible to configure a StubRequest to use a regular expression matcher to intercept URLs. The following example also shows a StubResponse that returns a certain status code:

func testStub() throws {
    let regex = try NSRegularExpression(pattern: "http://www.google.com/+", options: [])
    var stub = StubRequest(method: .GET, urlMatcher: RegexMatcher(regex: regex))
    stub.response = StubResponse(statusCode: 404)
    Hippolyte.shared.add(stubbedRequest: stub)
    Hippolyte.shared.start()

    myFictionalDataSource.get(URL(string: "http://www.google.com/foo.html")!) {
        
    }
}

There are convenient Builder classes for both requests and responses:

func testStub() {
    let response = StubResponse.Builder()
        .stubResponse(withStatusCode: 204)
        .addHeader(withKey: "X-Foo", value: "Bar")
        .build()
    let request = StubRequest.Builder()
        .stubRequest(withMethod: .GET, url: URL(string: "http://www.apple.com")!)
        .addResponse(response)
        .build()
    
    
}

Remember to tear down stubbing in your tests:

override func tearDown() {
    super.tearDown()
    Hippolyte.shared.stop()
}

You can configure your stub response in a number of ways, such as having it return different HTTP status codes, headers, and errors.

License

Hippolyte is released under the MIT license. See LICENSE for details

About

HTTP Stubbing in Swift

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • Swift 79.9%
  • Ruby 18.5%
  • Objective-C 1.6%