使用 OCMock 来预期类别方法会产生“[NSProxy doesNotRecognizeSelector”...]”
Posted
技术标签:
【中文标题】使用 OCMock 来预期类别方法会产生“[NSProxy doesNotRecognizeSelector”...]”【英文标题】:Using OCMock to expect category methods yields "[NSProxy doesNotRecognizeSelector"...]" 【发布时间】:2009-10-31 10:03:57 【问题描述】:我正在使用OCMock 尝试测试 NSURLConnection 的行为。这是不完整的测试:
#include "GTMSenTestCase.h"
#import <OCMock/OCMock.h>
@interface HttpTest : GTMTestCase
- (void)testShouldConnect;
@end
@implementation HttpTest
- (void)testShouldConnect
id mock = [OCMockObject mockForClass:[NSURLConnection class]];
NSURL *url = [NSURL URLWithString:@"http://www.google.com"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:mock startImmediately:NO];
[[mock expect] connection:connection didReceiveResponse:OCMOCK_ANY];
@end
当使用类别方法模拟类时,委托方法 connection:didReceiveresponse: 是,我收到错误:
Unknown.m:0:0 Unknown.m:0: error: -[HttpTest testShouldConnect] : *** -[NSProxy doesNotRecognizeSelector:connection:didReceiveResponse:] called!
有人遇到过这个问题吗?
【问题讨论】:
【参考方案1】:看起来你已经创建了一个 NSURLConnection 的模拟对象。但是,NSProxy 警告是正确的,NSURLConnection 对象没有选择器 connection:didReceiveResponse: - 这是一个传递给实现协议的对象的选择器。
你需要模拟一个实现 NSURLConnectionDelegate 的对象。由于委托协议指定 connection:didReceiveResponse: 你不应该得到一个错误:)
我对 OCMock 没有太多经验,但这似乎消除了编译错误:
@interface ConnectionDelegate : NSObject
- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;
@end
@implementation ConnectionDelegate
- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
@end
@interface ConnectionTestCase : SenTestCase
@end
@implementation ConnectionTestCase
- (void)testShouldConnect
id mock = [OCMockObject mockForClass:[ConnectionDelegate class]];
NSURL *url = [NSURL URLWithString:@"http://www.google.com"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:mock startImmediately:NO];
[[mock expect] connection:connection didReceiveResponse:OCMOCK_ANY];
@end
希望这会有所帮助,
山姆
【讨论】:
【参考方案2】:当使用 GCC 选项 COPY_PHASE_STRIP
设置为 YES
编译项目库时遇到此错误,因此符号不可见。然后针对该库运行测试,无法看到需要存根的方法设置 COPY_PHASE_STRIP=NO
修复了问题
【讨论】:
以上是关于使用 OCMock 来预期类别方法会产生“[NSProxy doesNotRecognizeSelector”...]”的主要内容,如果未能解决你的问题,请参考以下文章