菜鸟教程小白 发表于 2022-12-11 17:29:40

ios - 从 Storyboard 中模拟 UIViewController


                                            <p><p>我有一个关于在来自 Storyboard 的单元测试中模拟 UIViewController 的问题。我在 <code>setUp()</code> 方法中像这样从 Storyboard 加载了 ViewController ,这很好:</p>

<pre><code>var exampleVC: ExampleViewController!

override func setUp() {
    super.setUp()

    exampleVC = storyboard.instantiateViewControllerWithIdentifier(&#34;exampleVC&#34;) as! ExampleViewController
    UIApplication.sharedApplication().keyWindow?.rootViewController = exampleVC
    let _ = exampleVC.view
}
</code></pre>

<p>但是,问题是如何在 <code>exampleVC</code> 中模拟/覆盖方法。我试图改为创建一个 ExampleViewController 子类并在测试方法中创建模拟类,如下所示:</p>

<pre><code>func testExampleMethod() {
    class ExampleViewControllerMock: ExampleViewController {
      var testMethodWasCalled: Bool = false

      override func testMethod() {
            testMethodWasCalled = true
      }
    }

    let exampleVCMock = ExampleViewControllerMock()
    exampleVCMock.testMethod()

    XCTAssertTrue(exampleVCMock.testMethodWasCalled)
}
</code></pre>

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

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

<p>感谢任何建议。</p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>乔·本顿!在尝试测试此类场景时,您可以从您在 setUp 上实例化的真实 ViewController 中借用所有 UI 依赖项,并将它们应用到您的模拟 ViewController 中。</p>

<p>例如,如果你有一个 UIButton 和一个 UITableView:</p>

<pre><code>// exampleVC is your real UIViewController loaded on setUp.

mockViewController.loginButton = exampleVC.loginButton
mockViewController.tableView = exampleVC.tableView
</code></pre>

<p>从现在开始,您甚至可以使用这些 UI 元素来验证某些内容。</p></p>
                                   
                                                <p style="font-size: 20px;">关于ios - 从 Storyboard 中模拟 UIViewController,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/39470075/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/39470075/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - 从 Storyboard 中模拟 UIViewController