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
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.