2016-05-03 65 views
2

我正在添加下面的代碼。我想看看這些單元測試的例子。我對此很新,所以任何幫助都會很棒!請提供代碼!謝謝如何對下列方法進行單元測試?

//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

這不是你可以編寫單元測試的東西。單元測試適用於模型類,但是單元測試視圖和控制器根據定義是不可能的 - 它們主要通過將幾個部分連接在一起工作,而單元測試僅測試單個部分。

你可以看看UI tests。在這裏問自己的一個重要問題是:從長遠來看,爲這種情況編寫UI測試所耗費的能量是否會比通過手動測試案例可能花費的能量小?簡單地寫一篇描述某些需要手工測試的案例的文本文檔並不是一個失敗,比如在發佈之前。和UI測試相比,我會說它通常更有效。

+0

視圖和視圖控制器可使用XCTestCases(單元測試)進行測試。我發現單元測試視圖控制器非常有用。誠然,達到100%的覆蓋率幾乎是不可能的,可能不值得,但測試代碼的關鍵部分肯定有價值。 –

1

你可以模擬它向上

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 
    } 
} 
相關問題