8

このコードを考えてみてください。これは機能します(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番目のコード例は、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ですか?

4

1 に答える 1

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はどこに渡されますか?受信者はそれに何をしていますか?

于 2012-09-27T21:49:42.327 に答える