[英]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.