Skip to content

Instantly share code, notes, and snippets.

@jaderfeijo
Forked from pk/ExampleTest.m
Created January 5, 2022 09:19
Show Gist options
  • Save jaderfeijo/1fc3ba0499af2a07701c8b6c23d1735f to your computer and use it in GitHub Desktop.
Save jaderfeijo/1fc3ba0499af2a07701c8b6c23d1735f 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment