Skip to content

Instantly share code, notes, and snippets.

@reborg
Forked from pk/ExampleTest.m
Created December 17, 2011 19:36
Show Gist options
  • Save reborg/1491162 to your computer and use it in GitHub Desktop.
Save reborg/1491162 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_getClassMethod(aNewClass, aNewMethod);
method_exchangeImplementations(originalMethod, mockMethod);
aBlock();
method_exchangeImplementations(mockMethod, originalMethod);
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment