我无法获得 Cocoa Touch 静态库的 XCTestCase 单元测试,它依赖于使用 imageNamed
的代码来工作。
我将我的图像“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"];
如何为使用 imageNamed
的代码编写单元测试?
最佳答案
在 XCTest 中,您不在 mainBundle 中。因此,从您的 XCTest 包中获取图像。
(此解决方案适用于 iOS8+)
对象
[UIImage imageNamed:@"..." inBundle:[NSBundle bundleForClass:[self class]] compatibleWithTraitCollection:nil];
swift
UIImage(named: "...", in: Bundle(for: type(of: self)), compatibleWith: nil)
关于ios - 在 XCTestCase 中使用 UIImage imageNamed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22906462/