3

I want to write unit test cases (XCTest) in UIWebView/ Webkit- Swift Please post any helpful link, example, or tutorial.

Thank you. Shriram

Shriram Kadam
  • 394
  • 1
  • 4
  • 20

1 Answers1

1

A good way is to create fake navigation actions to call manually the delegate.

In this question you have a good example to write test cases of this way. unit-testing-wknavigationdelegate-functions

Example to test loading in navigation:

// setup
let fakeNavigation = WKNavigation()

delegateObject.refresh() // Set loading to true and init the web view
XCTAssertTrue(delegateObject.loading)

delegateObject.webView(webView, didFinish: fakeNavigation)
XCTAssertFalse(delegateObject.loading)

Example to test the policy:

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


XCTAssertEqual(receivedPolicy, theExpectedValue)
93sauu
  • 3,770
  • 3
  • 27
  • 43