Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 527
Dan Avatar asked Mar 16 '23 04:03

Dan


1 Answers

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)
  }
}
like image 93
Dan Avatar answered Mar 24 '23 23:03

Dan