在XCTestCase中使用UIImage imageNamed

Pie*_*ter 18 unit-testing objective-c uiimage ios xctest

我无法获得依赖于imageNamed用于工作的代码的Cocoa Touch静态库的XCTestCase单元测试.

我将我的图像"plane.png"添加到了测试目标,但[UIImage imageNamed]仍然保持返回nil.
当我在测试中明确指定图像的路径并从文件加载图像时,它确实有效.

NSString* imagePath = [[[NSBundle bundleForClass:[self class]] resourcePath] stringByAppendingPathComponent:@"plane.png"];
UIImage* imageWorks = [UIImage imageWithContentsOfFile:imagePath];

UIImage* imageStaysNil = [UIImage imageNamed:@"plane.png"];
Run Code Online (Sandbox Code Playgroud)

如何为使用的代码编写单元测试imageNamed

Cœu*_*œur 19

在XCTest中,您不在mainBundle中.所以从你的XCTest包中获取你的图像.

(此解决方案适用于iOS8 +)

ObjC

[UIImage imageNamed:@"..." inBundle:[NSBundle bundleForClass:[self class]] compatibleWithTraitCollection:nil];
Run Code Online (Sandbox Code Playgroud)

迅速

UIImage(named: "...", in: Bundle(for: type(of: self)), compatibleWith: nil)
Run Code Online (Sandbox Code Playgroud)