Little hack to help with testing

Want the ability to switch in different test drivers, mock objects, or other test-specific behaviour? Here’s a pattern I came up with (about a year ago) to do that in a GNUstep test tool, which can readily be used in Cocoa:

NSString *driverClassName = [[NSUserDefaults standardUserDefaults] stringForKey: @"Class"];
Class driverClass = NSClassFromString(driverClassName);
id myDriver = [[driverClass alloc] init];

With a healthy dose of no, seriously, don’t do this in production code, you now have the ability to specify your test driver on the command-line like this:

$ ./myTestingTool -Class GLTestDriver

This uses the oft-neglected behaviour of NSUserDefaults, in which it parses the executable’s command-line arguments to create a defaults domain, higher in priority than even the user’s preferences file. You can use that behaviour in a graphical app too, where it comes in handy when working in Xcode. It then uses a combination of the runtime’s duck typing and introspection capabilities to create an instance of the appropriate class.

This entry was posted in cocoa, gnustep, objc, openstep, test. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.