How to unit-test this custom UITextField in Swift?

别等时光非礼了梦想. 提交于 2019-12-12 22:08:45

问题


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?


回答1:


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)
  }
}


来源:https://stackoverflow.com/questions/31887848/how-to-unit-test-this-custom-uitextfield-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!