在Swift中重构后,测试UIViewController失败

时间:2015-10-08 11:43:19

标签: ios swift unit-testing uiviewcontroller

我尝试在Swift中测试ViewController时遇到了不同的结果。

第一个代码通过测试。

@testable import VideoAudioExtractor
import XCTest

class SecondViewControllerTest: XCTestCase {

let storyBoardName = "Main"
let viewControllerIdentifier = "SecondViewController"

override func setUp() {
    super.setUp()
    // Put setup code here. This method is called before the invocation of each test method in the class.
}

func testSelectAudioButtonIsConnected () {
    let sut = UIStoryboard(name: storyBoardName, bundle: nil).instantiateViewControllerWithIdentifier("SecondViewController") as! SecondViewController
    let dummy = sut.view
    if let unpwarppedOptional = sut.selectAudioButton {
        XCTAssertEqual(unpwarppedOptional,sut.selectAudioButton, "correct value")
    }
    else {
        XCTFail("Value isn't set")
    }
}

override func tearDown() {
    // Put teardown code here. This method is called after the invocation of each test method in the class.
    super.tearDown()
}

}

如果我重构测试并将视图控制器的创建移动到实例变量,则测试在Line中失败

@testable import VideoAudioExtractor
import XCTest

class SecondViewControllerTest: XCTestCase {

let storyBoardName = "Main"
let viewControllerIdentifier = "SecondViewController"
var sut : SecondViewController {
    return UIStoryboard(name: storyBoardName, bundle: nil).instantiateViewControllerWithIdentifier("SecondViewController") as! SecondViewController
}

override func setUp() {
    super.setUp()
    // Put setup code here. This method is called before the invocation of each test method in the class.
}

func testSelectAudioButtonIsConnected () {

    let dummy = sut.view
    if let unpwarppedOptional = sut.selectAudioButton {
        XCTAssertEqual(unpwarppedOptional,sut.selectAudioButton, "correct value")
    }
    else {
        XCTFail("Value isn't set")
    }
}

override func tearDown() {
    // Put teardown code here. This method is called after the invocation of each test method in the class.
    super.tearDown()
}

}

1 个答案:

答案 0 :(得分:1)

你需要像这样声明它'懒惰':

    lazy var sut : SecondViewController ...

这样它只会在第一次访问时创建。

代码中发生的事情是,每次访问sut属性时,都会创建一个新的SecondViewController实例。

当您访问sut.selectAudioButton时,您可以使用sut.view创建一个实例,并创建一个完全不同的实例。第二个实例没有加载它的视图,因为你没有调用.view!