开发者

Xcode Unit Testing - Accessing Resources from the application's bundle?

开发者 https://www.devze.com 2022-12-29 13:14 出处:网络
I\'m running into an issue and I wanted to confirm that I\'m doing things the correct way. I can test simple things with my SenTestingKit tests, and that works okay.I\'ve set up a Unit Test Bundle an

I'm running into an issue and I wanted to confirm that I'm doing things the correct way.

I can test simple things with my SenTestingKit tests, and that works okay. I've set up a Unit Test Bundle and set it as a dependency on the main application target. It successfully runs all tests whenever I press cmd+B.

Here's where I'm running into issues. I have some XML files that I need to load from the resources folder as part of the application. Being a good unit tester, I want to write unit tests around this to make sure that they are loading properly.

So I have some code that looks like this:

NSString *filePath = [[NSBundle mainBundle] 
    pathForResource:@"foo" ofType:@"xml"];

This works when the application runs, but during a unit test, mainBundle points to the wrong bundle, so this line of code returns nil.

So I changed it up to utilize a known class like this:

NSString *filePath = [[NSBundle bundleForClass:[Config class]] 
    pathForResource:@"foo" ofType:@"xml"];

This doesn't work either, because in order for the test to even compile code like this, it Config needs to be part of the Unit Test Target. If I add that, then the bundle for that class becomes the Unit Test bundle. (Ugh!)

Am I approaching this th开发者_如何学JAVAe wrong way?


While trying to reproduce your problem it hit me: Have you tried just adding your resources to your test bundle? Would that cause any problems for you? I did exactly that, and it worked great for me. For example:

Code:

- (void)testBundleLoading {
  NSLog(@"Main Bundle Path: %@", [[NSBundle mainBundle] bundlePath]);

  for (NSBundle *bundle in [NSBundle allBundles]) {
    NSLog(@"%@: %@", [bundle bundleIdentifier], 
                     [bundle pathForResource:@"fire" ofType:@"png"]);
  }
}

Output:

2010-05-05 14:31:05.961 otest[16970:903] Main Bundle Path: /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator3.1.3.sdk/Developer/usr/bin
2010-05-05 14:31:05.962 otest[16970:903] (null): (null)
2010-05-05 14:31:05.963 otest[16970:903] com.freetimestudios.KayakKingTests: /Volumes/FreeTime/KayakKing/build/Debug-iphonesimulator/KayakKingTests.octest/fire.png

I hope this helps.


I ran into this problem with Xcode 4 and my problem was that I had an old Xcode 3 project and somehow the info plist for the test target had gone missing. I added a new UnitTests-Info.plist to the project and I was suddenly able to retrieve resources again.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号