NetworkServiceMock

public final class NetworkServiceMock : NetworkService

Mocks a NetworkService. You can configure expected results or errors to have a fully functional mock.

Example:

//Given
let networkServiceMock = NetworkServiceMock()
let resource: Resource<String> = //

//When
networkService.request(
   resource,
   onCompletion: { string in /*...
  • Count of all started requests

    Declaration

    Swift

    public var requestCount: Int { get }
  • Last executed request

    Declaration

    Swift

    public var lastRequest: URLRequest? { get }
  • All executed requests.

    Declaration

    Swift

    public private(set) var lastRequests: [URLRequest]
  • Set this to hava a custom networktask returned by the mock

    Declaration

    Swift

    public var nextNetworkTask: NetworkTask?
  • Creates an instace of NetworkServiceMock

    Declaration

    Swift

    public init()
  • Fetches a resource asynchronously from remote location. Execution of the requests starts immediately. Execution happens on no specific queue. It dependes on the network access which queue is used. Once execution is finished either the completion block or the error block gets called. You decide on which queue these blocks get executed.

    Example:

    let networkService: NetworkService = //
    let resource: Resource<String> = //
    
    networkService.request(queue: .main, resource: resource, onCompletionWithResponse: { htmlText, response in
    print(htmlText, response)
    }, onError: { error in
    // Handle errors
    })
    

    Declaration

    Swift

    @discardableResult
    public func request<Result>(queue: DispatchQueue, resource: Resource<Result>, onCompletionWithResponse: @escaping (Result, HTTPURLResponse) -> Void,
                                onError: @escaping (NetworkError) -> Void) -> NetworkTask

    Parameters

    queue

    The DispatchQueue to execute the completion and error block on.

    resource

    The resource you want to fetch.

    onCompletionWithResponse

    Callback which gets called when fetching and transforming into model succeeds.

    onError

    Callback which gets called when fetching or transforming fails.

    Return Value

    a running network task

  • Will return an error to the current waiting request.

    Declaration

    Swift

    public func returnError(with error: NetworkError)

    Parameters

    error

    the error which gets passed to the caller

  • Will return a successful request, by using the given type T as serialized result of a request.

    Warning: This will crash if type T does not match your expected ResponseType of your current request

    Declaration

    Swift

    public func returnSuccess<T>(with serializedResponse: T, httpResponse: HTTPURLResponse = HTTPURLResponse())

    Parameters

    data

    the mock response from the server. Data() by default

    httpResponse

    the mock HTTPURLResponse from the server. HTTPURLResponse() by default