ios - 将单元测试目标添加到现有 Xcode 项目,无法在 bundle 中找到资源

标签 ios objective-c xcode unit-testing nsbundle

我已经将 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/

相关文章:

ios - SwiftyJSON : Can't read array value from JSON

iphone - 是否可以更改本地化的默认英语语言?

ios - 在调整 scrollView 的框架大小时,UIScrollView subview 的大小调整不正确

iphone - 看不到 iAd 框架

SwiftUI:如何自定义仅适用于 iPad 的工作表?

xcode - 为wxWidgets应用程序创建Xcode项目时出错

iphone - 自动调整大小完成后如何获取帧大小

ios - 条件的 OpenGL ES 最佳实践

ios - 从我的应用程序打开 iMessage

objective-c - 改变 cocoa DOMElement 的innerHTML