Frage

I am moving the frame of my UIView depending on the actual UIKeyboardState (Shown/Hidden). Now I'd like to write a Unit Test (XCTest) for this. Basically I want to check the frame of the UIView whenever the keyboard is shown or not.

This is my code for moving the UIView around, the methods get triggered via a NSNotification which I am registering in the 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];
}

Any idea how the unit test would look like ? I am very new to unit testing which is why i'm asking.

War es hilfreich?

Lösung

Here is a basic test case to test this functionality. You should replace UIViewController with your VC class. It is also not recommended to call -viewWillAppear: directly, but in the case of this specific unit test it could be alright.

-(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");
}

Bonus: The userInfo dictionary of UIKeyboardWillShowNotification includes a property that tells you the height of the keyboard; you could use this value instead of hardcoding your own offset. It also includes values for animation duration and timing curve, so your animation could more correctly follow that of the keyboard rather than hardcoding 0.3 seconds.

EDIT

To test the dynamic keyboard height, you would need to pass a userInfo dictionary with the UIKeyboardWillShowNotification that includes a fake frame for the keyboard:

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");
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top