在下面的代码中,如果我注释掉分配给 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/