Search code examples
iosswiftunit-testingxcode7xcode7-beta5

How to unit-test this custom UITextField in Swift?


I have created a custom UITextField like this

import Foundation
import UIKit

class NoZeroTextField: UITextField, UITextFieldDelegate {
    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.delegate = self
    }

    func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    if (string == "0" ) {
        //ignore input
        return false
    }
        return true
    }
}

I am trying to write unit test for the class but the problem is with passing NSCoder instance to the constructor. I cannot instantiate it or set it to nil. How can I unit-test this class?


Solution

  • I figured this out. Class under test:

    import Foundation
    import UIKit
    
    public class CustomTextField: UITextField, UITextFieldDelegate{
    
    required public init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.delegate = self
    }
    
     public func textField(textField: UITextField, shouldChangeCharactersInRange   range: NSRange, replacementString string: String) -> Bool {
        if (string == "X" ){
            //ignore input
            return false
        }
        return true
    }
    
    }
    

    The test itself:

    import UIKit
    import XCTest
    import TryCustom
    import Foundation
    
    class CustomTextFieldTests: XCTestCase {
    
      func testCustomTextField() {
        //pass in dummy non abstract NSCoder (NSKeyedUnarchiver)
        let cd = NSKeyedUnarchiver(forReadingWithData: NSMutableData())
        let c = CustomTextField(coder:cd)
        let result = c!.textField(c!, shouldChangeCharactersInRange: NSRange(), replacementString: "X")
        XCTAssertFalse(result)
      }
    }