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?
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)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With