Created
June 21, 2011 15:00
-
-
Save pk/1038034 to your computer and use it in GitHub Desktop.
Using method swizzling and blocks to test Class methods in Objective-C.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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 |
Thx reborg, that helped a lot!
As a newbie to objc, this gist is really going to make my life easier. Thanks!
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
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.