gpt4 book ai didi

ios - 向下转换/子类 UIViewController 用于单元测试中的模拟

转载 作者:搜寻专家 更新时间:2023-11-01 06:53:22 24 4
gpt4 key购买 nike

我有一个单元测试,我想创建 UIViewController 的子类版本,例如 Test1ViewController。具体来说,我想覆盖此类的 present 方法。

我有一个 View Controller 扩展,它根据类名实例化一个 View Controller 。

public class func instanceFromStoryboard<T>(storyboard: Storyboard) -> T {
return UIStoryboard(name: storyboard.rawValue, bundle: nil).instantiateViewController(withIdentifier: String(describing: T.self)) as! T
}

还有一个 Storyboard 类。

public enum Storyboard: String {
case main = "Main"
}

在我的单元测试中,我从 Test1ViewController 创建了一个子类。

class Test2ViewController: Test1ViewController {
var presented: Bool = false
override func present(_ viewControllerToPresent: UIViewController, animated flag: Bool, completion: (() -> Void)? = nil) {
presented = true
}
}

我如何使用我的扩展方法从 Storyboard 中检索 View Controller ,然后向下转换/子类化为 Test2ViewController

最佳答案

因为 Storyboard中的对象实际上是经过编码的对象,所以它们不能被解码并转换为其他任何对象。这是使用 Storyboard的缺点。你放入 Storyboard的内容就是你得到的内容。

如果可以,请使用基于 XIB 的 View Controller ,而不是基于 Storyboard的 View Controller 。使用 XIB(以及编程 View Controller ),测试可以实例化子类。

如果没有,那么您需要为您的 View Controller 引入一个后门。这将是不幸的,因为这意味着将测试代码混合到您的生产代码中。

关于ios - 向下转换/子类 UIViewController 用于单元测试中的模拟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55582063/

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