メソッドのスウィズリングまたは OCMock を使用して、両方をテストできます。
メソッドの入れ替えでは、まずテスト実装ファイルで次の変数を宣言します。
static NSString *passedString;
static id passedObject;
次に、スタブ メソッドを (テスト クラスで) 実装し、スウィズリングを実行します。
+ (void)stub_method:(NSString *)string object:(id)object
{
passedString = string;
passedObject = object;
}
- (void) test__with_method_swizzling
{
// Test preparation
passedString = nil;
passedObject = [NSNull null];// Whatever object to verify that we pass nil
Method originalMethod =
class_getClassMethod([CustomClass class], @selector(method:object:));
Method stubMethod =
class_getClassMethod([self class], @selector(stub_method:object:));
method_exchangeImplementations(originalMethod, stubMethod);
NSString * const kFakeString = @"fake string";
// Method to test
[CustomClass method:kFakeString];
// Verifications
STAssertEquals(passedString, kFakeString, nil);
STAssertNil(passedObject, nil);
method_exchangeImplementations(stubMethod, originalMethod);
}
しかし、OCMock を使用すると、もっと簡単な方法で同じことができます。
- (void) test__with_OCMock
{
// Test preparation
id mock = [OCMockObject mockForClass:[CustomClass class]];
NSString * const kFakeString = @"fake string";
[[mock expect] method:kFakeString object:nil];
// Method to test
[CustomClass method:kFakeString];
// Verifications
[mock verify];
}