gpt4 book ai didi

ios - 单元测试按钮单击不起作用

转载 作者:行者123 更新时间:2023-12-01 22:29:48 28 4
gpt4 key购买 nike

我以编程方式添加了一个按钮,我必须为自动化过程运行单元测试。我们没有太多的 UI 组件,所以我们不使用 UI 测试包。

在代码中添加按钮

self.proceedButton.frame = CGRectMake(0.0, 0.0, (buttonContainerWidth * 0.75), (buttonContainerHeight * 0.3));
self.proceedButton.center = CGPointMake(self.buttonContainer.center.x, CGRectGetHeight(self.proceedButton.frame));
self.proceedButton.layer.cornerRadius = CGRectGetHeight(self.proceedButton.frame) / 2;
self.proceedButton.layer.masksToBounds = YES;
self.proceedButton.titleLabel.font = proceedFont;
[self.proceedButton addTarget:self action:@selector(onAcceptClicked) forControlEvents:UIControlEventTouchUpInside];

测试:
[vc viewDidLoad];
NSString *selector = [[vc.proceedButton actionsForTarget:vc forControlEvent:UIControlEventTouchUpInside] firstObject];
XCTAssert([selector isEqualToString:@"onAcceptClicked"]);
[vc.proceedButton sendActionsForControlEvents: UIControlEventTouchUpInside];

如果我注释掉 [self.proceedButton addTarget:self action:@selector(onAcceptClicked) forControlEvents:UIControlEventTouchUpInside];,这将失败行,所以看起来测试是正确编写的。

然而 sendActionsForControlEvents:未进入 onAcceptClicked测试中的方法。

为什么会这样?单元测试是否可能在 onAcceptClicked 之前完成实际被调用?

最佳答案

这可能是因为您正在调用 [vc viewDidLoad]直接,其中Apple advises you not to do ,大概是因为在viewDidLoad之前进行了一堆设置最终被调用。

You should never call this method directly. The view controller calls this method when its view property is requested but is currently nil. This method loads or creates a view and assigns it to the view property.



相反,请尝试使用 XCTAssertNotNil(vc.view);一开始。这将尝试加载 View ,最终调用 viewDidLoad为您,并可能设置您的按钮,以便正确添加操作。

编辑 因此,如果它有帮助,我刚刚快速运行了这个测试,我可以验证方法 onAcceptClicked测试运行时在 View Controller 中调用。

viewDidLoad 中的按钮设置
CGRect frame = CGRectMake(50, 40, 30, 30);
self.proceedButton = [[UIButton alloc] initWithFrame:frame];
self.proceedButton.titleLabel.text = @"button!!!!";
[self.proceedButton addTarget:self action:@selector(onAcceptClicked) forControlEvents:UIControlEventTouchUpInside];
self.proceedButton.backgroundColor = [UIColor blackColor];
[self.view addSubview:self.proceedButton];

测试
-(void)testButton {
self.myVC = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"MyVC"];
XCTAssertNotNil(self.myVC.view);
NSString *selector = [[self.myVC.proceedButton actionsForTarget:self.myVC forControlEvent:UIControlEventTouchUpInside] firstObject];
XCTAssert([selector isEqualToString:@"onAcceptClicked"]);
[self.myVC.proceedButton sendActionsForControlEvents: UIControlEventTouchUpInside];
}

关于ios - 单元测试按钮单击不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37057598/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com