我已经将 Cocoa Touch Unit Testing Bundle 类型的新目标添加到现有的 iOS 项目、一个测试用例和一些我需要进行测试的 jpg 文件。
我正在尝试使用以下代码从测试包中加载图像:
@implementation PhotosViewController_Tests : XCTestCase
-(void)addImage:(NSString *)imageName
{
NSBundle *bundle = [NSBundle bundleForClass:[self class]];
NSString *imagePath = [bundle pathForResource:imageName ofType:@"jpg"];
UIImage *image = [UIImage imageWithContentsOfFile:imagePath];
...
}
但是,bundle 返回主包,而不是测试包,并且 imagePath 和图像为 nil。
我可以从主包中成功加载图像(使用此代码),但我不明白为什么 bundleForClass 返回 mainBundle 而不是单元测试包。
我打印了 [NSBundle allBundles]
并且我也得到了主包:
"NSBundle </var/mobile/Applications/uuid/Photos Light.app> (loaded)"
我想这与在创建项目后添加单元测试目标有关,但我想不出还有什么可以从测试包中加载图像。
最佳答案
尝试在你的测试目标中添加一个 NSBundle 扩展,看起来像这样......
@implementation NSBundle (MyAppTests)
+ (NSBundle *)testBundle {
// return the bundle which contains our test code
return [NSBundle bundleWithIdentifier:@"com.mycompany.MyAppTests"];
}
@end
然后当您需要从测试包中加载资源时,导入该类别,然后您的代码看起来像...
NSString *imagePath = [[NSBundle testBundle] pathForResource:imageName ofType:@"jpg"];
UIImage *image = [UIImage imageWithContentsOfFile:imagePath];
关于ios - 将单元测试目标添加到现有 Xcode 项目,无法在 bundle 中找到资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25536888/