我正在将文件从一个模块更改为另一个模块,因此在我的一项测试中开始出现此错误。虽然早些时候它工作得很好。
[Assert] UIApp 为零,这意味着我们无法将控制操作分派到他们的目标。如果此断言被命中,我们可能会在没有执行 UIApplicationMain() 的情况下到达这里,这可能意味着此代码未在应用程序中运行(可能是在没有主机应用程序的情况下运行的单元测试)并且不会按预期工作。
在代码中添加按钮 viewDidLoad()
private lazy var button: ABCTypeButton = {
let button = ABCTypeButton(title: viewModel.title, buttonType: .Payment).withAutoLayout()
button.accessibilityLabel = viewModel.title
button.accessibilityIdentifier = "paymentButton"
button.resetTintColor()
button.addTarget(self, action: #selector(ABCViewController.action1), for: .touchUpInside)
button.addTarget(self, action: #selector(ABCViewController.action2), for: .touchDown)
button.addTarget(self, action: #selector(ABCViewController.action3), for: [.touchUpOutside, .touchDragExit])
return button
}()
@objc private func action1() {
// code
}
public class ABCTypeButton: UIControl {
let iconImageView = UIImageView()
let buttonTitleLabel = UILabel()
private let chevronImageView = UIImageView(image: Icon.navigateNext.image)
private let stackView = UIStackView().withAutoLayout()
public init(title buttonTitle: String,
buttonType: FeeButtonType,
height: CGFloat = Spacing.four) {
super.init(frame: CGRect.zero)
setupViews(buttonTitle, buttonType: buttonType)
setupConstraints(height: height)
}
}
尝试点击测试中的按钮。
func test() {
let viewController = ViewController(viewModel: viewModel)
let button = viewController.view.findViewByIdentifier("paymentButton") as! ABCTypeButton
// I Checked that button is not nil
button.sendActions(for: .touchUpInside)
XCTAssertEqual(viewController.value, button.accessibilityIdentifier)
}
目标方法 action1() 没有被调用
我刚刚遇到了这个问题,并为 touchUpInside 事件做了这个粗略的扩展。显然可以重构以接受您想要调用的任何事件。
extension UIButton {
public func touchUpInside(forTarget target: UIViewController) {
guard let action = actions(forTarget: target, forControlEvent: .touchUpInside)?.first else {
assertionFailure("could not find touchUpInside action for target")
return
}
target.perform(Selector(action))
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句