简体   繁体   中英

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.

Joe Benton! When trying to test such scenarios, you can borrow all UI dependencies from the real ViewController you instantiated on setUp and apply them into your mocked ViewController.

For instance, if you have a UIButton and a UITableView:

// exampleVC is your real UIViewController loaded on setUp.

mockViewController.loginButton = exampleVC.loginButton
mockViewController.tableView = exampleVC.tableView 

From now on you can even use these UI elements to validate something.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM