考虑一下这个代码是有效的(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>
这是使用OCMock for iOS。
当模拟为expect
时,为什么mockForProtocol
会失败?
答案 0 :(得分:2)
这很奇怪。我已将以下类添加到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传递给哪里?接收者做了什么?