gpt4 book ai didi

ios - 从 Storyboard模拟 UIViewController

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:57:42 24 4
gpt4 key购买 nike

我有一个关于在 Storyboard中模拟单元测试中的 UIViewController 的问题。我在 setUp() 方法中像这样从 Storyboard 中加载了 View Controller ,这很好:

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)
}

这种方法在测试中崩溃,因为 View 和其他 IBOutlets 在 exampleVCMock 上为 nil 并且当 View Controller 以这种方式实例化时不会加载(因此 exampleVC 需要从 Storyboard实例化).

所以问题是我如何从 Storyboard 中实例化 exampleVC(以便 socket 正确连接)但同时能够为我的单元测试覆盖方法/正确创建模拟?

感谢任何建议。

最佳答案

乔本顿!尝试测试此类场景时,您可以从在 setUp 上实例化的真实 ViewController 借用所有 UI 依赖项,并将它们应用到模拟的 ViewController 中。

例如,如果您有一个 UIButton 和一个 UITableView:

// exampleVC is your real UIViewController loaded on setUp.

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

从现在开始,您甚至可以使用这些 UI 元素来验证某些内容。

关于ios - 从 Storyboard模拟 UIViewController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39470075/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com