4

だから私は自分のクラスの1つに対してクラスメソッドが呼び出されることを期待できるようにしたい

@implementation CustomClass

+ (void)method:(NSString*)string{
    [[self class] method:string object:nil];

}

+ (void)method:(NSString *)string object:(id)object {
    //do something with string and object
}

@end

[CustomClass method:@""]電話して期待したいmethod: string:

メソッドのスウィズリングを試してみましたが、それはスタブにのみ役立つようです。

4

1 に答える 1

4

メソッドのスウィズリングまたは 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];
}
于 2013-10-16T15:32:52.160 に答える