Skip to content

Instantly share code, notes, and snippets.

@pk
Created June 21, 2011 15:00
Show Gist options
  • Save pk/1038034 to your computer and use it in GitHub Desktop.
Save pk/1038034 to your computer and use it in GitHub Desktop.
Using method swizzling and blocks to test Class methods in Objective-C.
#import "SenTestCase+MethodSwizzling.m"
@interface ExampleTest : SenTestCase {}
+ (BOOL)trueMethod;
+ (BOOL)falseMethod;
@end
@implementation ExampleTest
+ (BOOL)trueMethod { return YES; }
+ (BOOL)falseMethod { return NO; }
- (void)testMethodSwizzlingShouldCallAlternativeImplementation {
[self swizzleMethod:@selector(trueMethod) inClass:[self class]
withMethod:@selector(falseMethod) fromClass:[self class]
executeBlock:^{
assertThatBool([[self class] trueMethod], isEqualToBool(NO));
}]
}
@end
#include <objc/runtime.h>
@interface SenTestCase (MethodSwizzling)
- (void)swizzleMethod:(SEL)aOriginalMethod
inClass:(Class)aOriginalClass
withMethod:(SEL)aNewMethod
fromClass:(Class)aNewClass
executeBlock:(void (^)(void))aBlock;
@end
@implementation SenTestCase (MethodSwizzling)
- (void)swizzleMethod:(SEL)aOriginalMethod
inClass:(Class)aOriginalClass
withMethod:(SEL)aNewMethod
fromClass:(Class)aNewClass
executeBlock:(void (^)(void))aBlock {
Method originalMethod = class_getClassMethod(aOriginalClass, aOriginalMethod);
Method mockMethod = class_getInstanceMethod(aNewClass, aNewMethod);
method_exchangeImplementations(originalMethod, mockMethod);
aBlock();
method_exchangeImplementations(mockMethod, originalMethod);
}
@end
@reborg
Copy link

reborg commented Dec 17, 2011

Hi there,

cool trick, thanks for sharing. The example given should not work unless you extract the target method as
Method mockMethod = class_getClassMethod(aNewClass, aNewMethod);
If it's working then there is some trouble going on with equality of BOOLs. To test it, try to
[NSException raise:@"DEBUG" format:@"##### %@", mockMethod];
right after line 18. It should be null.

@letsdev
Copy link

letsdev commented Feb 9, 2012

Thx reborg, that helped a lot!

@nheinric
Copy link

nheinric commented Jul 2, 2012

As a newbie to objc, this gist is really going to make my life easier. Thanks!

@felixhammerl
Copy link

the problem with this is if the test case you put into the block fails, you will not "deswizzle" the method. this is likely to mess up your other test cases. that's why i prefer to do the swizzling and cleanup stuff in the -setUp and -tearDown...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment