我刚刚开始熟悉使用XCTestCase编写测试,并且正在探索它的功能。我有一个简单的(如果是人为的)应用程序,加载一个带有按钮和文本框的屏幕。选择textfield时,视图控制器填充textfield:
public func textFieldDidBeginEditing(_ textField: UITextField) {
    textField.text = "abcd"
}在按下按钮时,我还具有选择字段的功能:
@IBAction public func selectField(_ sender: Any?) {
    print("button press")
    textfield.becomeFirstResponder()
}测试用例中的代码,使用vc.button.sendActions(for: .touchUpInside)编程地点击按钮。
但是,textfield似乎不会成为第一个响应者,因此不会调用委托方法。下面是完整的测试用例类:
var vc: ViewController!
override func setUp() {
    let sb = UIStoryboard(name: "Main", bundle: nil)
    vc = sb.instantiateInitialViewController() as? ViewController
    _ = vc.view
}
override func tearDown() {
}
func test_textfieldPopulatesOnSelection() {
    vc.button.sendActions(for: .touchUpInside)
    let expectation = XCTestExpectation(description: "waiting for textfield to become first responder")
    DispatchQueue.main.asyncAfter(deadline: .now() + 5.0) {
        print("textfield.text: \(self.vc.textfield.text ?? "")")
        expectation.fulfill()
    }
    wait(for: [expectation], timeout: 13.0)
}虽然我意识到我可能将UI测试和单元测试的概念混为一谈,但我仍然好奇为什么不调用我的委托方法。
发布于 2018-11-19 23:49:29
在单元测试中不调用委托方法。测试需要调用委托方法,就像Cocoa调用它们一样。
因此,要测试textFieldDidBeginEditing(_),单元测试需要显式调用它。
https://stackoverflow.com/questions/53380233
复制相似问题