Skip to content

Instantly share code, notes, and snippets.

@alexito4
Last active August 29, 2015 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexito4/85b6508f351e9d834463 to your computer and use it in GitHub Desktop.
Save alexito4/85b6508f351e9d834463 to your computer and use it in GitHub Desktop.
Add XCTest at runtime
#import <Foundation/Foundation.h>
#import "Smiler.h"
@interface Amazing : NSObject <Smiler>
@end
#import "Amazing.h"
@implementation Amazing
- (BOOL)smile
{
return NO;
}
@end
#import <Foundation/Foundation.h>
#import "Smiler.h"
@interface Happy : NSObject <Smiler>
@end
#import "Happy.h"
@implementation Happy
- (BOOL)smile
{
return YES;
}
@end
#import <Foundation/Foundation.h>
@protocol Smiler <NSObject>
- (BOOL)smile;
@end
#import <UIKit/UIKit.h>
#import <XCTest/XCTest.h>
#import <objc/runtime.h>
#import "Smiler.h"
@interface testingTests : XCTestCase
@end
@implementation testingTests
+ (void)initialize
{
Class metaclass = self.class;
BOOL success = class_addMethod(metaclass, @selector(testRuntime), (IMP)runtimeSmilerTest, "v@:");
NSLog(@"------------ Added %d", success);
}
void
runtimeSmilerTest(id self, SEL _cmd) {
NSArray *classes = [testingTests findClassesConformingToProtocol:@protocol(Smiler)];
NSLog(@"Smiler classes: %@", classes);
for (Class class in classes) {
id<Smiler> smiler = [[class alloc] init];
NSLog(@"|||||||||||||| Runtime test! %@", class);
XCTAssert([smiler smile], @"Fake! Pass");
}
}
+ (NSArray *)findClassesConformingToProtocol:(Protocol *)protocol
{
int numberOfClasses = objc_getClassList(NULL, 0);
Class *classes;
classes = (Class *)malloc(sizeof(Class) * numberOfClasses);
objc_getClassList(classes, numberOfClasses);
NSMutableArray *conformingClasses = [NSMutableArray array];
for (NSInteger i = 0; i < numberOfClasses; i++) {
Class lClass = classes[i];
if (class_conformsToProtocol(lClass, protocol)) {
[conformingClasses addObject:classes[i]];
}
}
free(classes);
return [conformingClasses copy];
}
- (void)setUp {
[super setUp];
}
- (void)tearDown {
[super tearDown];
}
- (void)testExample {
// This is an example of a functional test case.
XCTAssert(YES, @"Pass");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment