OCMock - 部分模拟 [UIAlertView alloc]

2024-03-12

我有一个问题OCMockiOS 框架。我本质上是想嘲笑UIAlertView's initWithTitle:message:delegate... 方法。下面的示例不起作用,因为当我调用时,未返回存根返回值initWithTitle method.

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

但是,如果我使用相同的想法,它确实有效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");
}

我注意到的一件事是该方法“forwardInvocationForRealObject:" in "OCPartialMockObject.m“ 期间被调用NSDictionary initWithContentsOfFile打电话,但不是在UIAlertViewinitWithTitle 调用。

这可能是一个OCMock bug?


这是一个更新的示例,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];

由某些事件的回调触发警报是很常见的。等待的一种方法是使用 verifyWithDelay,请参阅https://github.com/erikdoe/ocmock/pull/59 https://github.com/erikdoe/ocmock/pull/59.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

OCMock - 部分模拟 [UIAlertView alloc] 的相关文章

随机推荐