Rob*_*Rob 7 unit-testing objective-c ocmock ios xctest
我正在浏览一个应用程序并添加单元测试.该应用程序使用故事板编写,并支持iOS 6.1及更高版本.
我已经能够毫无问题地测试所有常用的返回方法.但是我目前难以接受我想要执行的某项测试:
基本上我有一个方法,让我们称之为doLogin:
- (IBAction)doLogin:(UIButton *)sender {
// Some logic here
if ( //certain criteria to meet) {
variable = x; // important variable set here
[self performSegueWithIdentifier:@"memorableWord" sender:sender];
} else {
// handler error here
}
Run Code Online (Sandbox Code Playgroud)
所以我想测试是否调用segue并设置变量,或者加载MemorableWord视图控制器并且其中的变量是正确的.在doLogin方法中设置的变量将传递到prepareForSegue方法中的memorableWord segues的目标视图控制器.
我有OCMock设置和工作,我也使用XCTest作为我的单元测试框架.有没有人能够进行单元测试以涵盖这种情况?
对于这个领域的信息来说,Google和SO似乎相当简陋.很多关于简单基本测试的例子与iOS测试中更复杂的现实无关.
你走在正确的轨道上,你的测试想要检查:
因此,您实际上应该触发从登录按钮到执行Segue的完整流程:
- (void)testLogin {
LoginViewController *loginViewController = ...;
id loginMock = [OCMockObject partialMockForObject:loginViewController];
//here the expect call has the advantage of swallowing performSegueWithIdentifier, you can use forwardToRealObject to get it to go all the way through if necessary
[[loginMock expect] performSegueWithIdentifier:@"memorableWord" sender:loginViewController.loginButton];
//you also expect this action to be called
[[loginMock expect] doLogin:loginViewController.loginButton];
//mocking out the criteria to get through the if statement can happen on the partial mock as well
BOOL doSegue = YES;
[[[loginMock expect] andReturnValue:OCMOCK_VALUE(doSegue)] criteria];
[loginViewController.loginButton sendActionsForControlEvents:UIControlEventTouchUpInside];
[loginMock verify]; [loginMock stopMocking];
}
Run Code Online (Sandbox Code Playgroud)
您需要为“criteria”实现一个属性,以便有一个可以使用“expect”来模拟的 getter。
重要的是要认识到“expect”只会模拟 1 次对 getter 的调用,后续调用将失败并显示“调用了意外的方法...”。您可以使用“存根”来模拟所有调用,但这意味着它将始终返回相同的值。