user6510422 user6510422 - 4 months ago 10
Swift Question

Why does the view property have to be assigned to a variable?

In the following code if I comment out the variable assigned to the view property, the tests fail. The line I'm referring to is:

_=sut.view


However when that line of code is uncommented, the tests pass. Why is it even necessary?

Here is the full unit test:

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)
}


}

dan dan
Answer

View controllers don't load their view until the first time the view property is accessed, so assigning the view to a variable will load it.

If the view isn't loaded then none of the outlets will be hooked up so sut.tableView will be nil and your tests will fail.

Comments