单元测试WKNavigationDelegate函数 [英] Unit testing WKNavigationDelegate functions

查看:153
本文介绍了单元测试WKNavigationDelegate函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个实现一些WKNavigationDelegate函数的UIViewController,并且我想对这些函数中的逻辑进行单元测试.这是一个示例:

I have a UIViewController that implements some WKNavigationDelegate functions, and I want to unit test the logic in these functions. Here's an example:

func webView(_ webView: WKWebView,
             decidePolicyFor navigationAction: WKNavigationAction,
             decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
    guard let url = navigationAction.request.url else {
        decisionHandler(.cancel)
        return
    }

    if url.absoluteString != "https://my-approved-url" {
        decisionHandler(.cancel)
        return
    }

    decisionHandler(.allow)
}

我希望我的单元测试确保基于WKNavigationAction的request.url使用正确的WKNavigationActionPolicy调用DecisionHandler.

I'd like my unit test to make sure decisionHandler is called with the right WKNavigationActionPolicy based on the request.url of the WKNavigationAction.

但是,我不知道如何测试此功能.当我运行测试项目时,在Web视图上调用.load()不会触发委托函数.我也尝试过直接调用此函数进行测试,但是似乎无法实例化我自己的新WKNavigationAction(.request为只读).

I can't figure out how to test this function, however. Calling .load() on the webview does not trigger the delegate functions when I'm running my test project. I have also tried to call this function directly to test it, but it doesn't seem to be possible to instantiate a new WKNavigationAction of my own (.request is read-only).

在WKNavigationDelegate函数中进行单元测试逻辑的正确方法是什么?

What is the right way to unit test logic in WKNavigationDelegate functions?

推荐答案

在单元测试的上下文中,直接调用委托方法是最合适的方法.您可以子类化WKNavigationAction,并将该类的实例作为输入参数传递给委托方法:

Directly calling the delegate method is the most appropriate approach in the context of a unit test. You can subclass WKNavigationAction, and pass an instance of that class as input argument to the delegate method:

class FakeNavigationAction: WKNavigationAction {
    let testRequest: URLRequest
    override var request: URLRequest {
        return testRequest
    }

    init(testRequest: URLRequest) {
        self.testRequest = testRequest
        super.init()
    }
}

稍后,在单元测试中:

// setup
var receivedPolicy: WKNavigationActionPolicy?
let fakeAction = FakeNavigationAction(testRequest: ...)

// act
delegateObject.webView(webView, decidePolicyFor: fakeAction, decisionHandler: { receivedPolicy = $0 })

// assert
XCTAssertEqual(receivedPolicy, theExpectedValue)

另一种方法是为request吸气,因为WKNavigationAction是一个Objective-C类,但是这更像是一个骇人听闻的解决方案.

Another approach would be to swizzle the getter for request, since WKNavigationAction is an Objective-C class, however that's more of a hacky solution.

这篇关于单元测试WKNavigationDelegate函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆