如何在Swift中对该自定义UITextField进行单元测试? [英] How to unit-test this custom UITextField in Swift?

查看:105
本文介绍了如何在Swift中对该自定义UITextField进行单元测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了这样的自定义UITextField

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

我正在尝试为该类编写单元测试,但是问题在于将NSCoder实例传递给构造函数.我无法实例化它或将其设置为nil.如何对该课程进行单元测试?

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?

推荐答案

我知道了.被测课程:

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

这篇关于如何在Swift中对该自定义UITextField进行单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆