user6510422 user6510422 - 2 months ago 5
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:


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() {
// 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



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


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

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


dan dan

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.