Unit testing WKNavigationDelegate functions

后端 未结 1 1417
北荒
北荒 2020-12-19 04:47

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         


        
相关标签:
1条回答
  • 2020-12-19 04:51

    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()
        }
    }
    

    Later on, in the unit test:

    // setup
    var receivedPolicy: WKNavigationActionPolicy?
    let fakeAction = FakeNavigationAction(testRequest: ...)
    
    // act
    delegateObject.webView(webView, decidePolicyFor: fakeAction, decisionHandler: { receivedPolicy = $0 })
    
    // assert
    XCTAssertEqual(receivedPolicy, theExpectedValue)
    

    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.

    0 讨论(0)
提交回复
热议问题