gpt4 book ai didi

ios - OCMock - 部分模拟 [UIAlertView alloc]

转载 作者:可可西里 更新时间:2023-11-01 06:20:47 25 4
gpt4 key购买 nike

我在使用 iOS 的 OCMock 框架时遇到问题。我本质上是在尝试模拟 UIAlertViewinitWithTitle:message:delegate... 方法。下面的示例在我调用 initWithTitle 方法时未返回 stub 返回值的意义上不起作用。

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

我注意到的一件事是,“OCPartialMockObject.m”中的方法“forwardInvocationForRealObject:”在 NSDictionary 期间被调用initWithContentsOfFile 调用,但不是在 UIAlertView initWithTitle 调用期间。

这可能是 OCMock 错误吗?

最佳答案

这是一个更新的例子,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 .

关于ios - OCMock - 部分模拟 [UIAlertView alloc],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20037834/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com