Skip to content

Instantly share code, notes, and snippets.

@revelation
Created February 24, 2010 23:20
Show Gist options
  • Star 15 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save revelation/314009 to your computer and use it in GitHub Desktop.
Save revelation/314009 to your computer and use it in GitHub Desktop.
@class GHTestCase;
@interface GHTestCase (Swizzle)
+ (id)sharedMock;
+ (void)setSharedMock:(id)newMock;
- (void)swizzle:(Class)target_class selector:(SEL)selector;
- (void)deswizzle;
@end
#import "GHUnit.h"
#import "GHTestCase+Swizzle.h"
#import <objc/objc-runtime.h>
id sharedMockPointer = nil;
@implementation GHTestCase (Swizzle)
+(id)sharedMock
{
return sharedMockPointer;
}
+(void)setSharedMock:(id)newMock
{
sharedMockPointer = newMock;
}
Method originalMethod = nil;
Method swizzleMethod = nil;
- (void)swizzle:(Class)target_class selector:(SEL)selector
{
originalMethod = class_getClassMethod(target_class, selector);
swizzleMethod = class_getInstanceMethod([self class], selector);
method_exchangeImplementations(originalMethod, swizzleMethod);
}
- (void)deswizzle
{
method_exchangeImplementations(swizzleMethod, originalMethod);
swizzleMethod = nil;
originalMethod = nil;
}
@end
@pk
Copy link

pk commented Jun 21, 2011

Hi I found your gist while searching for testing of the Class methods, it inspired me to implement the same concepts with blocks: git://gist.github.com/1038034.git

Thanks for sharing!

@revelation
Copy link
Author

That is awesome! Thanks for the update with blocks.

@jmoody
Copy link

jmoody commented Nov 2, 2011

Fantastic.

I had trouble compiling this for the simulator (Xcode 4.2).

If you change

#import <objc/objc-runtime.h 

to

#import <objc/runtime.h>

this will compile and run in both the simulator and devices.

Sorry for the multiple edits - goofed on the formatting.

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