ios - 为什么必须将 View 属性分配给变量?

标签 ios swift xcode xctest

在下面的代码中,如果我注释掉分配给 View 属性的变量,测试将失败。我指的是:

_=sut.view

然而,当该行代码被取消注释时,测试通过。为什么有必要?

这是完整的单元测试:

import XCTest
@testable import ToDo

class ItemListViewControllerTests: XCTestCase {

    var sut:ItemListViewController!

    override func setUp() {
        super.setUp()
        // Put setup code here. This method is called before the invocation of each test method in the class.
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        sut = storyboard.instantiateViewControllerWithIdentifier("ItemListViewController") as! ItemListViewController

        _=sut.view

    }

    override func tearDown() {
        // Put teardown code here. This method is called after the invocation of each test method in the class.
        super.tearDown()
    }
    func test_TableViewIsNotNilAfterViewDidLoad(){
        XCTAssertNotNil(sut.tableView.dataSource)
        XCTAssertTrue(sut.tableView.dataSource is ItemListDataProvider)

    }

    func testViewDidLoad_ShouldSetTableViewDelegate(){
        XCTAssertNotNil(sut.tableView.delegate)
        XCTAssertTrue(sut.tableView.delegate is ItemListDataProvider)
    }

    func testViewDidLoad_ShouldSetDelegateAndDataSourceToSameObject(){
        XCTAssertEqual(sut.tableView.dataSource as? ItemListDataProvider, sut.tableView.delegate as? ItemListDataProvider)
    }


}

最佳答案

View Controller 在第一次访问 view 属性之前不会加载它们的 View ,因此将 view 分配给变量将加载它。

如果未加载 View ,则不会连接任何 socket ,因此 sut.tableView 将为 nil,您的测试将失败。

关于ios - 为什么必须将 View 属性分配给变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38664889/

相关文章:

ios - 本地化 iOS Info.plist 隐私字符串

iphone - 如何使用 UITextAlignment 将 UITableViewCell 中的文本在 Swift 中左右对齐

swift - 当我尝试在 AudioKit 播放器之间切换时遇到问题

iphone - xcode 5 : What's the best way to go back and forth between top of editor and where you were before?

ios - Storyboard中的奇怪行为(运行应用程序时缺少 View )

ios - 是否可以使用 iOS SDK 在 Amazon Cognito 中更改用户名?

ios - Xcode 警告符号 - 带有白色圆圈的黄色三角形?

ios - 如何在 Swift 中使用拉取刷新?

ios - 如何将 View 底线的中心设置为主视图的中心点?

swift - 如何在swift中比较CGPoints?