2014-08-27 77 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]; 
相關問題