繁体   English   中英

UIKeyboardState 更改的 UIViewController 框架的单元测试

[英]Unit-test for UIViewController's frame changed by UIKeyboardState

我正在根据实际的UIKeyboardState (显示/隐藏)移动我的UIView的框架。 现在我想为此编写一个单元测试( XCTest )。 基本上,无论何时显示键盘,我都想检查UIView的框架。

这是我用于移动UIView的代码,这些方法通过我在viewWillAppear中注册的NSNotification触发:

- (void)keyboardWillShow:(NSNotification *)notification
{
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.3];
    [self.view setFrame:CGRectMake(0, -kOFFSET_FOR_KEYBOARD, self.view.frame.size.width, self.view.frame.size.height)];
    [UIView commitAnimations];
}

- (void)keyboardWillHide:(NSNotification *)notification
{
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.3];
    [self.view setFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    [UIView commitAnimations];
}

知道单元测试的样子吗? 我对单元测试很陌生,这就是我问的原因。

这是测试此功能的基本测试用例。 您应该用您的 VC class 替换UIViewController 也不建议直接调用-viewWillAppear:但在这个特定的单元测试的情况下,它可能没问题。

-(void)testKeyboardShown
{
    UIViewController* controller = [[UIViewController alloc] init];

    [controller viewWillAppear:YES];

    [[NSNotificationCenter defaultCenter] postNotificationName:UIKeyboardWillShowNotification object:nil];

    XCTAssertEqual(controller.view.frame.origin.y, -kOFFSET_FOR_KEYBOARD, "View should move up");

    [[NSNotificationCenter defaultCenter] postNotificationName:UIKeyboardWillHideNotification object:nil];

    XCTAssertEqual(controller.view.frame.origin.y, 0, "View should move down");
}

奖励: UIKeyboardWillShowNotification 的 userInfo 字典包含一个告诉你键盘高度的属性; 你可以使用这个值而不是硬编码你自己的偏移量。 它还包括 animation 持续时间和时序曲线的值,因此您的 animation 可以更正确地遵循键盘的值,而不是硬编码 0.3 秒。

编辑

要测试动态键盘高度,您需要使用 UIKeyboardWillShowNotification 传递 userInfo 字典,其中包含键盘的假框架:

CGRect keyboardFrame = CGRectMake(0, 0, 0, 20);

[[NSNotificationCenter defaultCenter] postNotificationName:UIKeyboardWillShowNotification object:nil userInfo:@{ UIKeyboardFrameBeginUserInfoKey : [NSValue valueWithCGRect:keyboardFrame] }];

XCTAssertEqual(controller.view.frame.origin.y, -keyboardFrame.size.height, "View should move up");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM