【问题标题】:Using UIImage imageNamed inside XCTestCase在 XCTestCase 中使用 UIImage imageNamed
【发布时间】:2014-05-19 08:16:04
【问题描述】:

我无法获得 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 的代码编写单元测试?

【问题讨论】:

    标签: ios objective-c unit-testing uiimage xctest


    【解决方案1】:

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

    (此方案适用于iOS8+)

    ObjC

    [UIImage imageNamed:@"..." inBundle:[NSBundle bundleForClass:[self class]] compatibleWithTraitCollection:nil];
    

    斯威夫特

    UIImage(named: "...", in: Bundle(for: type(of: self)), compatibleWith: nil)
    

    【讨论】:

    • 这个新功能确实使用了系统图片缓存,不像imageWithContentsOfFile,所以在iOS8+可以测试。仅仅为了能够对代码进行单元测试而必须更改所有 imageNamed 调用虽然并不理想,但它会做到的。
    • @Fonix 在 swift 4.0、4.1 和 4.2 中,type(of: self) 工作正常,无需更改。
    • @Cœur 你是对的,它确实有效,我不确定我之前做了什么,但它给了我一个编译错误并且巧合地改变了type(of: self)让它为我工作所以我只是假设就是这样,也许只是 xcodes 错误警告没有及时更新
    【解决方案2】:

    接受的答案对我不起作用;就是这样。

    let image = UIImage(contentsOfFile: 
        Bundle(for: type(of: self))
        .path(forResource: "plane", ofType: "png")!)!
    

    【讨论】:

      【解决方案3】:

      由于您的 xctest 项目的行为类似于不同的项目,因此还必须为 xctest 添加您的 .png 文件。

      将您的 plane.png 图像也添加到 xctest 项目中。 确保你已经检查过

      使用相同的代码对我来说效果很好

      【讨论】:

      • 图像被添加到测试目标(如果不是,我认为从文件加载不会起作用?)
      • 对我不起作用,我在测试一个“cocoa touch 静态库”,所以资源不能添加到静态库本身,也许就是这个区别?
      • 你的图片添加到静态库了吗?
      • 不,您不能真正将资源添加到静态库中,请参阅developer.apple.com/library/ios/technotes/iOSStaticLibraries/…
      • 我创建了一个新的应用程序项目,它确实可以工作,但不适用于静态库。澄清了问题,感谢您帮助我缩小问题范围
      猜你喜欢
      • 1970-01-01
      • 2012-01-28
      • 2011-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多