Xcode单元测试 - 从应用程序包中访问资源?

Ben*_*man 15 iphone xcode unit-testing bundle objective-c

我遇到了一个问题,我想确认我正在以正确的方式做事.

我可以使用SenTestingKit测试测试简单的东西,这样可以正常工作.我已经设置了一个单元测试包并将其设置为对主应用程序目标的依赖.每按一次cmd + B,它都会成功运行所有测试.

这是我遇到问题的地方.我有一些XML文件,我需要从资源文件夹加载作为应用程序的一部分.作为一个优秀的单元测试人员,我想围绕这个进行单元测试,以确保它们正确加载.

所以我有一些看起来像这样的代码:

NSString *filePath = [[NSBundle mainBundle] 
    pathForResource:@"foo" ofType:@"xml"];
Run Code Online (Sandbox Code Playgroud)

这在应用程序运行时有效,但在单元测试期间,mainBundle指向错误的包,因此这行代码返回nil.

所以我把它改为使用这样一个已知的类:

NSString *filePath = [[NSBundle bundleForClass:[Config class]] 
    pathForResource:@"foo" ofType:@"xml"];
Run Code Online (Sandbox Code Playgroud)

这也不起作用,因为为了使测试甚至像这样编译代码,它Config需要成为单元测试目标的一部分.如果我添加,那么该类的包将成为单元测试包.(啊!)

我是以错误的方式接近这个吗?

Nat*_*ror 20

在尝试重现您的问题时,它突然袭击了我:您是否尝试过将资源添加到测试包中?这会给你带来什么问题吗?我做到了这一点,它对我很有用.例如:

码:

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

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

输出:

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
Run Code Online (Sandbox Code Playgroud)

我希望这有帮助.