Go to file
417-72KI b3d5108826 fix script 2023-05-13 02:46:39 +09:00
.github update matrix 2023-05-13 01:57:36 +09:00
Sources/StubNetworkKit rename package 2022-05-09 00:13:32 +09:00
Tests/StubNetworkKitTests rename package 2022-05-09 00:13:32 +09:00
scripts fix script 2023-05-13 02:46:39 +09:00
.gitignore create package base 2022-04-28 00:49:10 +09:00
LICENSE Create LICENSE 2022-05-03 01:37:05 +09:00
Makefile Bump version to 0.2.0 2023-05-13 02:44:09 +09:00
Package.swift switch release flag to false 2023-05-13 02:44:10 +09:00
README.md Bump version to 0.2.0 2023-05-13 02:44:09 +09:00
StubNetworkKit.podspec Bump version to 0.2.0 2023-05-13 02:44:09 +09:00

README.md

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.2.0"),

CocoaPods

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, APIKit or Moya exist as test-cases in StubNetworkKitTests.swift.

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