'Is it possible to mock a function imported from a Swift package?
I have written a simple Swift package called JwtApiClient that provides a few helper functions for making HTTP requests to JWToken-protected APIs that transfer data as JSON.
I am consuming one of these functions (postJsonDictionary) in another package:
import Foundation
import JwtApiClient
public func requestToken<T: Decodable>(
_ username: String,
_ password: String
) async throws -> T {
let endpoint = "/users/login" // in the actual code this is an instance of URLComponents
// not String but it's irrelevant here
let credentials = [
"email": username,
"password": password
]
// I'd like to be able to mock this call
return try await postJsonDictionary(endpoint!, credentials)
}
I was just wondering if it is possible to mock postJsonDictionary in a unit test to avoid making an underlying network request and to be able to assert on the parameters passed to it.
I have tried tricking my unit test into believing the function is a global but it doesn't work:
extension NSObject {
public func postJsonDictionary<T: Decodable>(_ url: URL!, _ dictionary: [String: Any]) async throws -> T {
try await Task.sleep(nanoseconds: 2 * 1_000_000_000)
let fakeTokenResponse: TokenResponse = TokenResponse(token: "fake-token")
return fakeTokenResponse as! T
}
}
// XCTestCase below
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
