문제

So I want to be able to expect a class method being called for one of my classes

@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

and I want to call [CustomClass method:@""] and expect method: string:

I've tried method swizzling but it seems like that is only useful for stubbing.

도움이 되었습니까?

해결책

You can test that both using method swizzling or OCMock.

With method swizzling, first of all we declare the following variables in your test implementation file:

static NSString *passedString;
static id passedObject;

Then we implement a stub method(in the test class) and go with the swizzling:

+ (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);
}

But we can accomplish the same with OCMock in a much simpler way:

- (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];
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top