Eduardo Arenas Prada Eduardo Arenas Prada - 1 year ago 194
iOS Question

NSURL to file path in test bundle with XCTest

I am trying to write an iOS app using TDD and the new XCTest framework. One of my methods retrieves a file from the internet (given a NSURL object) and stores it in the user's documents. The signature of the method is similar to:

- (void) fetchAndStoreImage:(NSURL *)imageUrl

I'm trying to write the test for this method in a way that it doesn't fail if there is no connection to the internet. My approach (taken from a previous question) is to call the method using a NSURL to an image in the local file system.

When a new project with unit tests enabled is created, the Tests directory has a subdirectory named 'Supporting Files'. I suppose that is where my test images should go. My question is how can I get a NSURL object that points to an image in this directory, as I wouldn't want test images to be bundled with the application. Any help is appreciated.

Answer Source

In fact, the [NSBundle mainBundle] when running a UnitTest is not the path of your app, but is /Developer/usr/bin, so this will not work.

The way to get resources in a unit test is here: OCUnit & NSBundle

In short, use:

[[NSBundle bundleForClass:[self class]] resourcePath]

or in your case:

[[NSBundle bundleForClass:[self class]] resourceURL]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download