简体   繁体   English

从故事板模拟UIViewController

[英]Mocking UIViewController from storyboard

I have a question about mocking a UIViewController in my Unit Tests that is from the storyboard. 我有一个关于在情节提要中模拟UIViewController的问题。 I have the view controller loaded from storyboard like this in the setUp() method which is fine: 我在setUp()方法中像这样从情节提要加载了视图控制器,这很好:

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 . 但是,问题是我该如何在exampleVC模拟/重写方法。 I have tried to instead create a ExampleViewController subclass and create the mock class in the test method like this: 我试图改为创建ExampleViewController子类,并在测试方法中创建模拟类,如下所示:

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). 这种方法在测试时崩溃,因为视图和其他IBOutlet在exampleVCMock上为零,并且以这种方式实例化视图控制器时不会加载(因此,必须从情节提要中实例化exampleVC)。

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? 因此,问题是如何从情节提要中实例化exampleVC(以便插座正确连接),但同时又能够覆盖方法/为单元测试正确创建模拟?

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. 在尝试测试这种情况时,可以从在setUp上实例化的实际ViewController借用所有UI依赖项,并将其应用于模拟的ViewController中。

For instance, if you have a UIButton and a UITableView: 例如,如果您有一个UIButton和一个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. 从现在开始,您甚至可以使用这些UI元素来验证某些内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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