• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

ios - 从 Storyboard 中模拟 UIViewController

[复制链接]
菜鸟教程小白 发表于 2022-12-11 17:29:40 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

我有一个关于在来自 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)
}

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

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

感谢任何建议。



Best Answer-推荐答案


乔·本顿!在尝试测试此类场景时,您可以从您在 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/

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap