[英]Mocking UIViewController from storyboard
我有一个关于在情节提要中模拟UIViewController的问题。 我在setUp()
方法中像这样从情节提要加载了视图控制器,这很好:
var exampleVC: ExampleViewController!
override func setUp() {
super.setUp()
exampleVC = storyboard.instantiateViewControllerWithIdentifier("exampleVC") as! ExampleViewController
UIApplication.sharedApplication().keyWindow?.rootViewController = exampleVC
let _ = exampleVC.view
}
但是,问题是我该如何在exampleVC
模拟/重写方法。 我试图改为创建ExampleViewController子类,并在测试方法中创建模拟类,如下所示:
func testExampleMethod() {
class ExampleViewControllerMock: ExampleViewController {
var testMethodWasCalled: Bool = false
override func testMethod() {
testMethodWasCalled = true
}
}
let exampleVCMock = ExampleViewControllerMock()
exampleVCMock.testMethod()
XCTAssertTrue(exampleVCMock.testMethodWasCalled)
}
这种方法在测试时崩溃,因为视图和其他IBOutlet在exampleVCMock
上为零,并且以这种方式实例化视图控制器时不会加载(因此,必须从情节提要中实例化exampleVC)。
因此,问题是如何从情节提要中实例化exampleVC(以便插座正确连接),但同时又能够覆盖方法/为单元测试正确创建模拟?
任何建议表示感谢。
乔·本顿! 在尝试测试这种情况时,可以从在setUp上实例化的实际ViewController借用所有UI依赖项,并将其应用于模拟的ViewController中。
例如,如果您有一个UIButton和一个UITableView:
// exampleVC is your real UIViewController loaded on setUp.
mockViewController.loginButton = exampleVC.loginButton
mockViewController.tableView = exampleVC.tableView
从现在开始,您甚至可以使用这些UI元素来验证某些内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.