Loading Files for Unit Testing in Cocoa

Adding files to your unit testing bundle helps when you’re unit testing file behavior or when you have a lot of test data. This post shows you how to load files from the unit testing bundle to help you unit test Cocoa applications.

Before You Code

The first thing you must do is get your test files in the unit testing bundle. Add the test files to your project. When adding the files, add them to the unit testing target, not the application target. Make sure the test files are part of the unit testing target’s Copy Bundle Resources build phase. When you build the project, the test files will be copied to the unit testing bundle’s Resources directory.

Loading a File from the Unit Testing Bundle

To load an individual file call NSBundle’s pathForResource: method. The following code loads a test XML file from the unit testing bundle:

NSBundle *unitTestBundle = [NSBundle bundleForClass:[self class]];
NSString* xmlFilename = [unitTestBundle pathForResource:@"XMLTestFile" ofType:nil];
NSData* xmlData = [[NSData alloc] initWithContentsOfFile:xmlFilename];

Opening a File Wrapper

To open a file wrapper, call NSBundle’s URLForResource: method to find the file wrapper. Call NSFileWrapper’s initWithURL: method to open the file wrapper. The following code opens a file wrapper from the unit testing bundle:

NSBundle *unitTestBundle = [NSBundle bundleForClass:[self class]];
NSURL* testFileURL = [unitTestBundle URLForResource:@"FileWrapperTest" withExtension:@"wrap"];
NSFileWrapper* testFile = [[NSFileWrapper alloc] initWithURL:testFileURL options:0 error:nil];

Substitute your file wrapper’s file extension for “wrap” in the URLForResource: call. Read my Working with Cocoa File Packages post for more information on working with file wrappers.

Keep in mind that the initWithURL: method was added in Mac OS X 10.6. If you’re running an older version of Mac OS X, call NSFileWrapper’s initWithPath: method, which was deprecated in 10.6.

Comments (1) | Trackback

One Response to “Loading Files for Unit Testing in Cocoa”

  1. Mike Zornek says:

    Thanks for posting this.

Leave a Reply

What is 11 + 6 ?
Please leave these two fields as-is:
IMPORTANT! To be able to proceed, you need to solve the following simple math (so we know that you are a human) :-)
Powered by WordPress