我有一个名为
CertificatePinningDelegate
的自定义委托类,它符合 URLSessionDelegate
。我正在使用委托方法
urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void)
与服务器进行身份验证。现在我想为此编写一个单元测试。
我一直在尝试手动调用委托方法来传递自定义的
URLAuthenticationChallenge
对象,这似乎是不可能的。有谁知道有什么替代/更好的选择吗?
这是我目前用来测试我的 SecTrustValidator 的东西,它接受 SecTrust 对象并对其进行一些检查。您必须
await
网络调用。在委托方法中,将您需要的任何内容保存到测试对象,以便在网络调用成功后在测试中使用此信息。请记住,在测试中进行网络调用可能会导致不稳定。
let googleUrl = "https://google.com"
final class SSLCertTest: XCTestCase, URLSessionDelegate {
var secTrust: SecTrust!
private func getGoogle() async throws {
let urlSession = URLSession(
configuration: .default,
delegate: self,
delegateQueue: nil
)
let googleRequest = URLRequest(url: URL(string: googleUrl)!)
let _ = try await urlSession.data(for: googleRequest).0
}
func testIsValidSSLWithDomain() async throws {
try await getGoogle()
let validator = SecTrustValidator(with: secTrust)
XCTAssertTrue(try validator.isValidSSL(with: "google.com"))
}
func testIsValidSSL() async throws {
try await getGoogle()
let validator = SecTrustValidator(with: secTrust)
XCTAssertTrue(try validator.isValidSSL())
}
func urlSession(
_ session: URLSession,
didReceive challenge: URLAuthenticationChallenge
) async
-> (URLSession.AuthChallengeDisposition, URLCredential?) {
guard let serverTrust = challenge.protectionSpace.serverTrust else { return (.cancelAuthenticationChallenge, nil) }
self.secTrust = serverTrust
return (.useCredential, nil)
}
}