来自 func 的 TDD 数据未在 XCTest 案例中返回 Swift

TDD data from func not being returned in XCTest case Swift

这是我 QuickAddViewController.swift 文件中的内容

let exercisesData = ExerciseDatabase()

var workoutTypesDictionary = Dictionary<String,Dictionary<String,Array<String>>>()

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
    workoutTypesDictionary = self.exercisesData.exercisesByWorkoutType

}

func getWorkoutTypes() -> [String] {
    var workoutTypesArray : [String] = []
    for workoutType in workoutTypesDictionary.keys {
        workoutTypesArray.append(workoutType)
    }

    return workoutTypesArray
}

这是我的 QuickAddViewTest.swift 文件

class QuickAddViewTests: XCTestCase {

var quickAddViewController : QuickAddViewController!

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

    quickAddViewController = QuickAddViewController()
}

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

func testGetWorkoutTypes() {

    let workoutTypesArray = quickAddViewController.getWorkoutTypes()

    let expectedArray = ["Weight Training", "Sports & Recreation", "Body Weight", "Cardio"]

    print("Workout Array: \(workoutTypesArray)")

    print("Expected Array: \(expectedArray)")

    XCTAssertEqual(workoutTypesArray, expectedArray)

}

当我 运行 应用程序并打印 getWorkoutTypes() 时,函数 return 正确的值。但是,当我尝试 return testGetWorkoutTypes() 中的相同值时,没有任何内容得到 returned,我的测试失败了。

添加

quickAddViewController.loadViewIfNeeded()

这会导致连线情节提要连接(这使得其他测试成为可能)并触发对 viewDidLoad() 的回调。