我想为登录界面编写测试用例。我正在为登录操作编写测试用例。
这是我的代码:
- (IBAction)loginAction:(id)sender {
if ([[self.userNameTextField text] length] <=3 ||
[[self.passwordTextField text] length] <=3 ) {
UIAlertController *alert = [UIAlertController
alertControllerWithTitle:@"Error"
message:@"Username/Password \n length must be > 4 charecters"
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *action = [UIAlertAction
actionWithTitle:@"OK"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * _Nonnull action) {
[alert dismissViewControllerAnimated:true completion:nil];
}];
[alert addAction:action];
[self presentViewController:alert animated:true completion:nil];
} else {
// success case
}
}
Cedar Spec
describe(@"LoginViewController", ^{
__block LoginViewController *subject;
context(@"it should show the alert",^{
beforeEach(^{
subject = [LoginViewController instanceFromStoryboardForSpecs:subject identifier:@"login"];
UITextField *txtUserName = [UITextField new];
subject.userNameTextField = txtUserName;
subject.userNameTextField.text = @"DA";
[subject loginAction: nil];
});
it(@"it should be charecters < 3 ", ^{
subject.userNameTextField.text.length should be_lte(3);
});
it(@"when be charecters < 3 ", ^{
subject.presentedViewController should be_instance_of([UIAlertController class]);
UIAlertController *alertController = (id)subject.presentedViewController;
alertController.title should equal(@"Error"); // Important for proper styling
alertController.message should equal(@"Username/Password \n length must be > 4 charecters");
alertController.actions.count should equal(1);
alertController.preferredStyle should equal(UIAlertControllerStyleAlert);
UIAlertAction *cancelAction = alertController.actions.firstObject;
cancelAction.title should equal(@"OK");
});
});
});
但它在这里失败了 subject.presentedViewController应该是be_instance_of([UIAlertController class]);
任何人都可以帮助我理解编写测试用例吗?我使用了 Cedar WiKi ,但我无法理解如何为我的案例编写测试用例。
答案 0 :(得分:0)
第一个问题是,instanceFromStoryboardForSpecs
是做什么的?是否将您的视图控制器添加到UIWindow?否则,对presentViewController:animated:completion:
的任何调用都将失败,并显示一个错误(您在控制台中看到任何错误吗?),并且不会显示任何警报。
第二,我对您的代码的某些部分感到困惑:
您从情节提要中实例化了LoginViewController
,但是需要从代码中创建UITextField
吗?我希望它会沿着视图控制器加载。
我要分担责任:
// call validateUserName:password:, then either presentError: if needed
- (IBAction)loginAction:(id)sender
// login logic
- (void)loginWithUserName:(NSString *)userName password:(NSString *)password
// validation logic
- (BOOL)validateUserName:(NSString *)userName password:(NSString *)password
// use it every time you want to display error
- (BOOL)presentError:(NSString *)error
有了它,您可以单元测试(使用简单的XCTestCase)验证逻辑,如果需要的话,可以使用UI测试错误表示逻辑(可以重复使用以显示不同类型的错误)或与BDD测试用户一起使用整个场景都像您尝试过的那样。