ios - 如何为按钮点击编写单元测试?

标签 ios swift xctest xctestcase

我在这里尝试检查 View Controller 的单元测试用例。 - 我有一个带有按钮和标签的 View Controller 。 - 当你点击按钮时,它会调用另一个方法。它将数据提供给按钮操作标签文本更改。
- 我想检查那个按钮是否触发了那个方法?不添加函数的任何 bool 值或返回类型。

这是我的代码。

class ViewController: UIViewController {

    @IBOutlet weak var buttonFetch: UIButton?

    @IBOutlet weak var nameLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

    }

    @IBAction func fetchUser() {
        self.nameLabel.text = self.getUser()
    }

    func getUser() ->String {
        return User.data()
    }
}

struct User  {
    static func data()->String{
        return "Apple"
    }
}

这是我的测试用例

func testFetchUserAction() {
        controller.buttonFetch?.sendActions(for: .touchDown)
        // I want to test the method getUser from viewcontroller gets called or not
        // some thing like this XCTAssert(self.controller.getUser(),"not called")
        XCTAssertEqual(self.controller.nameLabel.text!, "Apple")

    }

最佳答案

你有没有试过像下面这样..

func testFetchUserAction() {

    self.controller.nameLabel.text = nil

    //Use this line, If you assigned touchUpInside to your button action
    controller.buttonFetch?.sendActions(for: .touchUpInside)

    //Use this line, If you assigned touchDown to your button action
    controller.buttonFetch?.sendActions(for: .touchDown)

    XCTAssert(self.controller.nameLabel.text != nil, "not called")

}

注意:要故意使测试用例失败,您可以更改 sendActions 中的 UIControl.Event

关于ios - 如何为按钮点击编写单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53756455/

相关文章:

ios - Objective C 等待带有信号量的循环 block

swift - 没有这样的模块

objective-c - 私有(private)枚举声明

jquery - iOS 上的 CSS3 和 jQuery 过渡 Flash

ios - JSON访问数组内的多个实例

arrays - 在 swift 3 中使用 Json

ios - KingFisher + UICollectionView + XCTest 与 NSURLSession 模拟不加载图像

swift - UI 测试包标识符和代码覆盖率

ios - 构建 XCTest 时找不到文件错误

iphone - 从appDelegate检索核心数据模型版本