我有一個與GitHub API集成的iOS應用程序。我正在測試我的OAuth
請求,它需要測試從GitHub API接收的代碼,我將用它來交換令牌。我如何測試調用iOS應用程序委託方法?
在我AppDelegate.swift
,我有以下的方法,它是用於在用戶授權我的應用程序使用他們的GitHub的帳戶來處理從GitHub回調:
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
return true
}
的步驟如下:
- 打開應用程序。
- 使用該URL授權GitHub帳戶訪問權限(https://github.com/login/oauth/authorize),會顯示一個
SFSafariViewController
實例,允許用戶按'授權'按鈕。 - GitHub將回調URL用於我向GitHub註冊應用程序時提供的應用程序,該應用程序發送通知以打開我的應用程序。
- 執行上述方法,其中我從
url
檢索code
參數。
但是,我堅持試圖找到一種方法來測試這一點,而不需要實際向GitHub API發出請求。我可以創建一個URL
實例來模擬GitHub爲我的應用程序提供的內容,但我想在不提供實際請求的情況下對其進行測試。
有沒有辦法單元測試這個,或者這是我不應該擔心的事情,因爲它是由操作系統來處理,而是隻測試我的代碼來解析code
參數的測試URL
?
UPDATE
服用之後喬恩的advice,我創建了一個測試類,讓我模擬動作GitHub的回調:
class GitHubAuthorizationCallbackTests: XCTestCase {
let delegate = AppDelegateMock()
func test_AuthorizationCallbackFromGitHub_ApplicationOpensURL() {
guard let url = URL(string: "xxxxxxxxxxxxxx://?code=********************") else { return XCTFail("Could not construct URL") }
let isURLOpened = delegate.application(UIApplication.shared, open: url)
XCTAssertTrue(isURLOpened, "URL is not opened from GitHub authorization callback. Expected URL to be opened from GitHub authorization callback.")
}
}
然後,我創建了AppDelegateMock.swift
使用,而不是AppDelegate.swift
,添加在打算執行GitHub回調時調用的預期方法:
import UIKit
class AppDelegateMock: NSObject, UIApplicationDelegate {
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
return true
}
}
測試通過,允許我測試我需要測試的邏輯,以處理從GitHub返回的參數code
int url
該方法的參數。