如何在 Swift 中对这个自定义 UITextField 进行单元测试?
How to unit-test this custom UITextField in Swift?
我创建了一个像这样的自定义 UITextField
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
}
}
我正在尝试为 class 编写单元测试,但问题在于将 NSCoder 实例传递给构造函数。我无法实例化它或将其设置为零。我如何对这个 class?
进行单元测试
我想通了。 Class 正在测试中:
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
}
}
测试本身:
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)
}
}
我创建了一个像这样的自定义 UITextField
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
}
}
我正在尝试为 class 编写单元测试,但问题在于将 NSCoder 实例传递给构造函数。我无法实例化它或将其设置为零。我如何对这个 class?
进行单元测试我想通了。 Class 正在测试中:
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
}
}
测试本身:
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)
}
}