swift - XCTestCase 中未调用 UITextFieldDelegate

标签 swift cocoa-touch xctest xctestcase

我刚刚开始熟悉使用 XCTestCase 编写测试并探索其功能。我有一个简单的(如果设计的)应用程序,它加载一个带有按钮和文本字段的屏幕。选择文本字段时, View Controller 填充文本字段:

public func textFieldDidBeginEditing(_ textField: UITextField) {
    textField.text = "abcd"
}

我还有在按下按钮时选择字段的功能:

@IBAction public func selectField(_ sender: Any?) {
    print("button press")
    textfield.becomeFirstResponder()
}

我的测试用例中的代码,使用 vc.button.sendActions(for: .touchUpInside) 以编程方式点击按钮

但是,文本字段似乎并没有成为第一响应者,因此没有调用委托(delegate)方法。以下是完整的测试用例类:

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 测试和单元测试的概念,但我仍然很好奇为什么我的委托(delegate)方法没有被调用。

最佳答案

单元测试中不调用委托(delegate)方法。由测试来调用委托(delegate)方法,就好像它们是由 Cocoa Touch 调用的一样。

因此要测试 textFieldDidBeginEditing(_),单元测试需要显式调用它。

关于swift - XCTestCase 中未调用 UITextFieldDelegate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53380233/

相关文章:

ios - 在 Xcode5 中使用 XCTest 时 AFNetworking 导致错误

iphone - 如何测试 sendsynchronousRequest : on XCTest

ios - 如何 UI 测试 UICollectionViewCell didSelect

ios - 如何获取 UITextView 中光标之前的字符?

ios - 如何使用 Collection View 单元格转到下一个 View ?

iphone - 如何从 NSMutableDictionary 中删除字典数组?

ios - 如何将数字转换为其枚举?

ios - 无法在 collectionView 中调用 dequeueReusableCellWithReuseIdentifier(collectionView : collectionViewLayout: sizeForItemAtIndexPath)

ios - Swift 2.1 核心数据 - 使用 setValue() 更新图像记录

objective-c - 如何在 Objective-C 中创建和调用基本方法?