Skip to content

Instantly share code, notes, and snippets.

@diogot
Created May 28, 2014 20:31
Show Gist options
  • Save diogot/fc4b987cfa8256dae2d1 to your computer and use it in GitHub Desktop.
Save diogot/fc4b987cfa8256dae2d1 to your computer and use it in GitHub Desktop.
XCTestCase (MethodSwizzling)
//
// XCTestCase+MethodSwizzling.h
//
// Created by Diogo Tridapalli on 5/28/14.
// Copyright (c) 2014 Diogo Tridapalli. All rights reserved.
//
#import <XCTest/XCTest.h>
@interface XCTestCase (MethodSwizzling)
- (void)swizzleClassMethod:(SEL)aOriginalMethod
inClass:(Class)aOriginalClass
withMethod:(SEL)aNewMethod
fromClass:(Class)aNewClass
executeBlock:(void (^)(void))aBlock;
- (void)swizzleInstanceMethod:(SEL)aOriginalMethod
inClass:(Class)aOriginalClass
withMethod:(SEL)aNewMethod
fromClass:(Class)aNewClass
executeBlock:(void (^)(void))aBlock;
@end
//
// XCTestCase+MethodSwizzling.m
//
// Created by Diogo Tridapalli on 5/28/14.
// Copyright (c) 2014 Diogo Tridapalli. All rights reserved.
//
#import "XCTestCase+MethodSwizzling.h"
#import <objc/runtime.h>
@implementation XCTestCase (MethodSwizzling)
- (void)swizzleInstanceMethod:(SEL)aOriginalMethod
inClass:(Class)aOriginalClass
withMethod:(SEL)aNewMethod
fromClass:(Class)aNewClass
executeBlock:(void (^)(void))aBlock
{
Method originalMethod = class_getInstanceMethod(aOriginalClass, aOriginalMethod);
Method mockMethod = class_getInstanceMethod(aNewClass, aNewMethod);
method_exchangeImplementations(originalMethod, mockMethod);
aBlock();
method_exchangeImplementations(mockMethod, originalMethod);
}
- (void)swizzleClassMethod:(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
@diogot
Copy link
Author

diogot commented May 28, 2014

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