OCMock - 部分模拟[UIAlertView alloc]

lar*_*mba 3 iphone objective-c ocmock ios

我遇到了OCMockiOS框架的问题.我基本上是试图嘲笑UIAlertViewinitWithTitle:message:delegate......方法.下面的示例在我调用initWithTitle方法时未返回存根返回值的意义上不起作用.

UIAlertView *emptyAlert = [UIAlertView new];
id mockAlert = [OCMockObject partialMockForObject:[UIAlertView alloc]];
[[[mockAlert stub] andReturn:emptyAlert] initWithTitle:OCMOCK_ANY message:OCMOCK_ANY delegate:nil cancelButtonTitle:OCMOCK_ANY otherButtonTitles:nil];

UIAlertView *testAlertReturnValue = [[UIAlertView alloc] initWithTitle:@"title" message:@"message" delegate:nil cancelButtonTitle:@"ok" otherButtonTitles:nil];
if(testAlertReturnValue == emptyAlert) {
    NSLog(@"UIAlertView test worked");
}
Run Code Online (Sandbox Code Playgroud)

但是,如果我使用相同的想法,它确实有效NSDictionary.

NSDictionary *emptyDictionary = [NSDictionary new];
id mockDictionary = [OCMockObject partialMockForObject:[NSDictionary alloc]];
[[[mockDictionary stub] andReturn:emptyDictionary] initWithContentsOfFile:OCMOCK_ANY];

NSDictionary *testDictionaryReturnValue = [[NSDictionary alloc] initWithContentsOfFile:@"test"];
if(testDictionaryReturnValue == emptyDictionary) {
    NSLog(@"NSDictionary test worked");
}
Run Code Online (Sandbox Code Playgroud)

我注意到的一件事是forwardInvocationForRealObject:OCPartialMockObject.m调用期间NSDictionary initWithContentsOfFile调用" "中的方法,而不是在UIAlertViewinitWithTitle调用期间调用.

这可能是个OCMock错误吗?

dB.*_*dB. 9

这是一个更新的例子,OCMock现在支持类模拟.

            id mockAlertView = [OCMockObject mockForClass:[UIAlertView class]];
            [[[mockAlertView stub] andReturn:mockAlertView] alloc];
            (void)[[[mockAlertView expect] andReturn:mockAlertView]
                   initWithTitle:@"Title"
                   message:@"Message"
                   delegate:OCMOCK_ANY
                   cancelButtonTitle:OCMOCK_ANY
                   otherButtonTitles:OCMOCK_ANY, nil];
            [[mockAlertView expect] show];

            // code that will display the alert here

            [mockAlertView verify];
            [mockAlertView stopMocking];
Run Code Online (Sandbox Code Playgroud)

通过对某些内容的回调触发警报是很常见的.等待它的一种方法是使用verifyWithDelay,请参阅https://github.com/erikdoe/ocmock/pull/59.