mardi 13 septembre 2016

Mocking UIViewController from storyboard

I have a question about mocking a UIViewController in my Unit Tests that is from the storyboard. I have the view controller loaded from storyboard like this in the setUp() method which is fine:

var exampleVC: ExampleViewController!

override func setUp() {
    super.setUp()

    exampleVC = storyboard.instantiateViewControllerWithIdentifier("exampleVC") as! ExampleViewController
    UIApplication.sharedApplication().keyWindow?.rootViewController = exampleVC
    let _ = exampleVC.view
}

However, the issue is how can I then mock/override methods in exampleVC. I have tried to instead create a ExampleViewController subclass and create the mock class in the test method like this:

func testExampleMethod() {
    class ExampleViewControllerMock: ExampleViewController {
        var testMethodWasCalled: Bool = false

        override func testMethod() {
            testMethodWasCalled = true
        }
    }

    let exampleVCMock = ExampleViewControllerMock()
    exampleVCMock.testMethod()

    XCTAssertTrue(exampleVCMock.testMethodWasCalled)
}

This approach crashes on the test as the view and other IBOutlets are nil on exampleVCMock and don't get loaded when the view controller is instantiated this way (so the exampleVC needs to be instantiated from storyboard).

So the question is how I can instantiate the exampleVC from storyboard (so the outlets are connected correctly) but at the same time be able to override methods/create the mock correctly for my unit tests?

Any advice appreciated thanks.

Aucun commentaire:

Enregistrer un commentaire