【问题标题】:Adding unit testing target to existing Xcode project, can't find resource in bundle将单元测试目标添加到现有 Xcode 项目,无法在包中找到资源
【发布时间】:2014-08-27 21:02:39
【问题描述】:

我已将 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 和 image 为 nil。

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

我打印了[NSBundle allBundles],我也得到了主包:

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

我猜这与创建项目后添加单元测试目标有关,但我不知道还有什么可以从测试包中加载图像。

【问题讨论】:

    标签: ios objective-c xcode unit-testing nsbundle


    【解决方案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];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-08
      相关资源
      最近更新 更多