我正在将文件从一个模块更改为另一个模块,这样我就开始在一个测试中遇到这个错误。而早些时候它工作得很好。
[断言]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()未被调用
最佳答案
我刚刚遇到了这个问题,并为touchupinder事件做了一个粗略的扩展。显然可以重构以接受您想调用的任何事件。
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))
}
}