0

I have a bit of trouble getting my test-suite up and running. Basically I added a new target to my application like so: Unit Testing Applications

As I want to test against my DA-classes and sqlite-database I use the following snipped to copy the database:

    // First, test for existence.
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:DATABASE_Path];
success = [fileManager fileExistsAtPath:writableDBPath];
if (success) return;
// The writable database does not exist, so copy the default to the appropriate location.
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:DATABASE_Path];
success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
if (!success) {
    NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
}

but as it seems, NSBundle doesn't return the path to the database as expected.

Is there a simple fix to this? I wasn't able to fix it in the last couple of hours - so my next shot is you guys.

Any help or suggestion is highly appreciated!

Thanks a lot!

Tom

Jasonw
  • 5,054
  • 7
  • 43
  • 48
Tom
  • 213
  • 3
  • 10

1 Answers1

1

I just hit the exact same issue, inheriting some code that does raw sqlite access in a very similar manner.

There are two issues here, and they answered elsewhere on SO.

Firstly, during testing NSBundle mainBundle doesn't return what you think it will, if you want code that depends on NSBundle mainBundle to work during unit test, you can replace it with

[NSBundle bundleForClass: [self class]]

I'm not sure if this is any less efficient ( probably), but it does work in unit test.

The second issue is that the document directory doesn't get referenced correctly, as the unit test isn't running inside the sand box. There are several ways of fixing this, but the easiest is just to create a documents directory in ~/Library/Application Support/iPhone Simulator/6.1/. Obviously, 6.1 is just an example.

References:-

OCUnit & NSBundle

NSHomeDirectory in iPhone unit test

BTW, I just love answering old questions.

Community
  • 1
  • 1
Gordon Dove
  • 2,537
  • 1
  • 22
  • 23