考虑下面的代码,它可以正常工作(loginWithEmail方法也可以正常使用):
_authenticationService = [[OCMockObject mockForClass:[AuthenticationService class]] retain];
[[_authenticationService expect] loginWithEmail:[OCMArg any] andPassword:[OCMArg any]];
与下面的代码:
_authenticationService = [[OCMockObject mockForProtocol:@protocol(AuthenticationServiceProtocol)] retain];
[[_authenticationService expect] loginWithEmail:[OCMArg any] andPassword:[OCMArg any]];
第二个代码示例在第2行失败,并显示以下错误:
*** -[NSProxy doesNotRecognizeSelector:loginWithEmail:andPassword:] called! Unknown.m:0: error: -[MigratorTest methodRedacted] : ***
-[NSProxy doesNotRecognizeSelector:loginWithEmail:andPassword:] called!
AuthenticationServiceProtocol声明该方法:
@protocol AuthenticationServiceProtocol <NSObject>
@property (nonatomic, retain) id<AuthenticationDelegate> authenticationDelegate;
- (void)loginWithEmail:(NSString *)email andPassword:(NSString *)password;
- (void)logout;
- (void)refreshToken;
@end
它是在该类中实现的:
@interface AuthenticationService : NSObject <AuthenticationServiceProtocol>
这是用于iOS的OCMock。
当模拟是
expect
时,为什么mockForProtocol
失败? 最佳答案
这很好奇。我已将以下类添加到iOS5示例项目中:
@protocol AuthenticationServiceProtocol
- (void)loginWithEmail:(NSString *)email andPassword:(NSString *)password;
@end
@interface Foo : NSObject
{
id<AuthenticationServiceProtocol> authService;
}
- (id)initWithAuthenticationService:(id<AuthenticationServiceProtocol>)anAuthService;
- (void)doStuff;
@end
@implementation Foo
- (id)initWithAuthenticationService:(id<AuthenticationServiceProtocol>)anAuthService
{
self = [super init];
authService = anAuthService;
return self;
}
- (void)doStuff
{
[authService loginWithEmail:@"x" andPassword:@"y"];
}
@end
@implementation ProtocolTests
- (void)testTheProtocol
{
id authService = [OCMockObject mockForProtocol:@protocol(AuthenticationServiceProtocol)];
id foo = [[Foo alloc] initWithAuthenticationService:authService];
[[authService expect] loginWithEmail:[OCMArg any] andPassword:[OCMArg any]];
[foo doStuff];
[authService verify];
}
@end
当我在Xcode版本4.5(4G182)中针对iPhone 6.0模拟器运行此程序时,测试通过。模拟对象的使用方式有何不同?在您的情况下,_authenticationService传递到哪里?接收者对此做了什么?
关于objective-c - OCMock,为什么我不能期望协议(protocol)中的方法?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12618320/