我有一个与GitHub API集成的iOS应用程序。我正在对我的OAuth请求进行单元测试,这需要测试从GitHub API接收代码,我将使用该代码交换令牌。
在我的AppDelegate.swift中,我有以下方法,用于处理GitHub回调,当用户授权我的应用程序使用他们的GitHub帐户时:
步骤如下:
测试通过,这样我就可以测试处理从GitHub返回的
在我的AppDelegate.swift中,我有以下方法,用于处理GitHub回调,当用户授权我的应用程序使用他们的GitHub帐户时:
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
return true
}
步骤如下:
- 打开应用程序。
- 使用授权 GitHub 帐户访问的 URL(https://github.com/login/oauth/authorize),实例化
SFSafariViewController
,允许用户按“授权”按钮。 - GitHub 使用我的注册应用程序时提供的回调 URL 向我的应用程序发送通知。
- 执行上述方法,从
url
中检索code
参数。
但是,我无法找到一种不需要实际向 GitHub API 发出请求的测试方法。我可以创建一个类似于 GitHub 提供给我的应用程序的 URL
实例,但我想在不进行实际请求的情况下进行测试。
是否有一种单元测试这个的方法,还是说这是由操作系统处理的,我只需测试解析测试 URL
的代码?
更新
在接受 Jon 的建议后,我创建了一个测试类,允许我模拟 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返回的
url
参数中的code
参数所需的逻辑。