2014-08-27 76 views
2

我已经添加了一个类型为可可触摸单元测试包的新目标到现有iOS项目,测试用例和一些我需要的jpg文件测试。将单元测试目标添加到现有的XCode项目中,找不到捆绑中的资源

我试图加载使用下面的代码测试包的图像:

@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]; 

    ... 
} 

然而,束返回主束,而不是测试包和ImagePath的和形象是零。

我可以成功地从主包(使用此代码)加载图像,但我不明白为什么bundleForClass返回mainBundle而不是单元测试。

我打印的[NSBundle allBundles]和我得到的主束以及:

"NSBundle </var/mobile/Applications/uuid/Photos Light.app> (loaded)" 

我猜它是与添加单元测试目标创建项目后,但我不图什么否则可以从测试包中加载图像。

谢谢

回答

1

尝试在您的测试目标添加一个扩展名一个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]; 
相关问题