我在这里尝试检查 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/