-
-
Save jaderfeijo/1fc3ba0499af2a07701c8b6c23d1735f to your computer and use it in GitHub Desktop.
Using method swizzling and blocks to test Class methods in Objective-C.
This file contains hidden or 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 hidden or 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment