I want to dynamically subclass a class (say NSString) and instantiate that subclass for testing purposes. How can I do that in Objective C?
views:
72answers:
1I suspect that you don't need to do what you're seeking to do, but without more specifics it's impossible to know for sure. Because Objective-C is a late-bound language, subclassing for testing purposes is rarely required. Instead, take a look at class categories or consider a redesign so that you can pass a test double (either stub, fake or mock) via a parameter of type id
or conforming to a protocol.
For interest, you can use objc_allocateClassPair(Class superclass, const char *name, size_t extraBytes)
to allocate a new class. You can add methods using class_addMethod(Class cls, SEL name, IMP imp, const char *types)
and ivars with class_addIvar(Class cls, const char *name, size_t size, uint8_t alignment, const char *types)
. Finally, you should register the new class using objc_registerClassPair(Class cls)
. Find out more in the Objective-C 2.0 Runtime Reference. If I find time, I'll test some code and post it here.