【发布时间】:2017-01-15 22:56:41
【问题描述】:
我有一个与 GitHub API 集成的 iOS 应用程序。我正在对我的 OAuth 请求进行单元测试,这需要测试从 GitHub API 接收到的代码,我将使用该代码来交换令牌。
在我的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 使用我在向 GitHub 注册应用程序时提供的应用程序回调 URL,它会发送通知以打开我的应用程序。
- 上面的方法执行完毕,我从
url中检索code参数。
但是,我一直在尝试找到一种方法来测试它,而无需实际向 GitHub API 发出请求。我可以创建一个 URL 实例来模仿 GitHub 为我的应用程序提供的内容,但我想在不发出实际请求的情况下对其进行测试。
有没有办法对此进行单元测试,或者这是我不应该担心的事情,因为它是由操作系统处理的,而是只测试我的代码以解析测试 URL 的 code 参数?
更新
在接受 Jon 的 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 参数和方法的 url 参数所需的逻辑。
【问题讨论】:
标签: ios unit-testing appdelegate