deh*_*len 3 unit-testing objective-c uiview ios xctest
我UIView根据实际UIKeyboardState(显示/隐藏)移动我的框架.现在我想为此编写一个单元测试(XCTest).基本上我想检查UIView键盘显示与否的框架.
这是我移动的代码UIView,方法通过NSNotification我在以下位置注册的方式触发viewWillAppear:
- (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];
}
Run Code Online (Sandbox Code Playgroud)
知道单元测试的样子吗?我对单元测试很新,这就是我要问的原因.
以下是测试此功能的基本测试用例.您应该替换UIViewController您的VC类.也不建议-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");
}
Run Code Online (Sandbox Code Playgroud)
奖励: UIKeyboardWillShowNotification的userInfo字典包含一个告诉你键盘高度的属性; 您可以使用此值而不是硬编码您自己的偏移量.它还包括动画持续时间和时间曲线的值,因此您的动画可以更准确地跟随键盘的动画,而不是硬编码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");
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2320 次 |
| 最近记录: |