StubNetworkKit

0.4.0

Stub your network requests in Swift
417-72KI/StubNetworkKit

What's New

0.4.0

2024-04-24T15:17:02Z

Breaking

  • Now requires Swift 5.8

What's Changed

  • Update actions/download-artifact action to v4 by @renovate in #34
  • Update actions/upload-artifact action to v4 by @renovate in #35
  • Update actions/cache action to v4 by @renovate in #36
  • Update 417-72KI/danger-swiftlint action to v5.10 by @renovate in #37
  • Update dependency 417-72KI/MultipartFormDataParser to from: "2.2.0" by @renovate in #38
  • Update dependency 417-72KI/MultipartFormDataParser to from: "2.2.1" by @renovate in #40
  • Drop Swift 5.7 by @417-72KI in #39

Full Changelog: 0.3.1...0.4.0

StubNetworkKit

CI GitHub release CocoaPods Version CocoaPods Platform GitHub license

100% pure Swift library to stub network requests.

100% pure Swift means,

  • No more Objective-C API
  • Testable also in other than Apple platform (e.g. Linux)

Installation

Swift Package Manager(recommended)

.package(url: "https://github.com/417-72KI/StubNetworkKit.git", from: "0.4.0"),

CocoaPods

Warning

watchOS support is unavailable in CocoaPods due to dependency.
If you want to use including watchOS, consider migrating to Swift Package Manager.

pod 'StubNetworkKit'

Preparation

Pure Swift is not supporting method-swizzling, therefore you have to enable stub explicitly.

If you are using URLSession.shared only, you can call registerStubForSharedSession() to enable stubs.

Otherwise, you should inject URLSessionConfiguration instance that stub is registered.

Sample codes with using Alamofire or APIKit exist in Sample.

Example

Basic

stub(Scheme.is("https") && Host.is("foo") && Path.is("/bar"))
    .responseJson(["message": "Hello world!"])

Switch response with conditional branches in request.

stub(Scheme.is("https") && Host.is("foo") && Path.is("/bar")) { request in
    guard request.url?.query == "q=1" else {
        return .error(.unexpectedRequest($0))
    }
    return .json(["message": "Hello world!"])
}

Using Result builder

stub {
    Scheme.is("https")
    Host.is("foo")
    Path.is("/bar")
    Method.isGet()
}.responseJson(["message": "Hello world!"])

Switch response with conditional branches in request.

stub {
    Scheme.is("https")
    Host.is("foo")
    Path.is("/bar")
    Method.isGet()
} withResponse: { request in
    guard request.url?.query == "q=1" else {
        return .error(.unexpectedRequest($0))
    }
    return .json(["message": "Hello world!"]) 
}

stub(url: "foo://bar/baz", method: .get)
    .responseData("Hello world!".data(using: .utf8)!)

Function chain

stub()
    .scheme("https")
    .host("foo")
    .path("/bar")
    .method(.get)
    .responseJson(["message": "Hello world!"])

More examples

If you are looking for more examples, look at StubNetworkKitTests.

Description

  • Swift Tools 5.8.0
View More Packages from this Author

Dependencies

Last updated: Sun May 05 2024 02:12:39 GMT-0900 (Hawaii-Aleutian Daylight Time)