lar*_*mba 3 iphone objective-c ocmock ios
我遇到了OCMock
iOS框架的问题.我基本上是试图嘲笑UIAlertView
的initWithTitle: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
调用" "中的方法,而不是在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];
Run Code Online (Sandbox Code Playgroud)
通过对某些内容的回调触发警报是很常见的.等待它的一种方法是使用verifyWithDelay,请参阅https://github.com/erikdoe/ocmock/pull/59.