如何对以下方法进行单元测试?

时间:2016-05-03 04:14:12

标签: ios xcode swift unit-testing uitextfield

我正在添加以下代码。我想看看这些单元测试的例子。我是新手,所以任何帮助都会很棒!请提供代码!感谢

 //Dismiss keyboard when tapping on screen
func tapGesture(gesture:UITapGestureRecognizer){

    romanNumeralTextfield.resignFirstResponder()

}


//When return key is tapped the keyboard is dismissed
func textFieldShouldReturn(textField: UITextField) -> Bool {
    romanNumeralTextfield.resignFirstResponder()
    return true
}


//Display keyboard
func keyboardWillShow(notification: NSNotification) {

    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
        self.view.frame.origin.y -= keyboardSize.height
    }

}


//Hide keyboard
func keyboardWillHide(notification: NSNotification) {
    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
        self.view.frame.origin.y += keyboardSize.height
    }
}

2 个答案:

答案 0 :(得分:1)

这不是你可以编写单元测试的东西。单元测试适用于模型类,但单元测试视图和控制器根据定义是不可能的 - 它们主要通过将多个部分连接在一起来工作,而单元测试仅测试单个部分。

您可以查看UI tests。在这里问自己的重要问题是:从长远来看,为这种情况编写UI测试所花费的能量是否会小于手动测试案例所花费的能量?在发布之前,简单地编写描述一些手动测试案例的文本文档并不是一个失败。与UI测试相比,我认为它通常更有效。

答案 1 :(得分:0)

你可以嘲笑它

override func setUp() {
    super.setUp()
}

override func tearDown() {
    super.tearDown()
}

func testTextFieldDidBeginEditingCalled() {

    let sampleTextField = MockTextField(frame: CGRectMake(20, 100, 300, 40))
    sampleTextField.placeholder = "Enter text here"
    sampleTextField.font = UIFont.systemFontOfSize(15)
    sampleTextField.borderStyle = UITextBorderStyle.RoundedRect
    sampleTextField.autocorrectionType = UITextAutocorrectionType.No
    sampleTextField.keyboardType = UIKeyboardType.Default
    sampleTextField.returnKeyType = UIReturnKeyType.Done
    sampleTextField.clearButtonMode = UITextFieldViewMode.WhileEditing;
    sampleTextField.contentVerticalAlignment = UIControlContentVerticalAlignment.Center

    sampleTextField.textFieldDidBeginEditing(sampleTextField)

    XCTAssertTrue(sampleTextField.completionInvoked, "should be true")
}

class MockTextField: UITextField, UITextFieldDelegate {

    var completionInvoked = false

    func textFieldDidBeginEditing(textField: UITextField) {
        print("TextField did begin editing method called")
        completionInvoked = true
    }
}