【问题标题】:NSImage from Asset Catalog in Test Target测试目标中资产目录中的 NSImage
【发布时间】:2018-08-31 11:09:07
【问题描述】:

我的单元测试目标需要加载图像资源以用于某些测试,但我无法加载它。

  1. 我在测试目标中创建了一个资产目录。
  2. 我在目录中添加了一个新的图像集资源,选中了“设备”中的“Mac”框,并将其源图像设置为两种分辨率(@1x 和@2x):

  1. 我已经检查了测试目标的“复制捆绑资源”构建阶段,它确实包含资产目录。

  2. 我查看了资产目录和图片集的目标成员,确实是测试目标。


运行测试时,我尝试使用如下代码加载图像:

guard let image = NSImage(named: NSImage.Name("TestSourceImage")) else {
    fatalError("Test Resource is Missing.")
}

...但是守卫失败了。

我也试过了:

let bundle = Bundle(for: MyClassTests.self)

guard let path = bundle.pathForImageResource(NSImage.Name("TestSourceImage")) else {
    fatalError("Test Resource is Missing.")
}

guard let image = NSImage(contentsOfFile: path) else {
    fatalError("Test Resource File is Corrupt.")
}

...但是第一个守卫失败(无法检索资源路径)。

两种格式我都试过了

NSImage.Name("TestSourceImage")

和:

NSImage.Name(rawValue: "TestSourceImage")

我也试过Bundle.urlForImageResource(_),但也失败了。


我见过类似的问题和答案,但它们要么适用于 iOS,要么适用于 app(主)捆绑包中的资源。

我错过了什么?


更新:

同时,我通过将我的测试图像添加为独立图像资源(不使用资产目录)并加载它来解决该问题使用以下代码:

let bundle = Bundle(for: MyClassTests.self)
guard let url = bundle.url(forResource: "TestSourceImage", withExtension: "png") else {
    fatalError("!!!")
}
guard let image = NSImage(contentsOf: url) else {
    fatalError("!!!")
}

在这种情况下,我不需要支持多种分辨率(我的图像是图像处理算法的来源;它已经被假定为必要的最高分辨率),即使我这样做了,我也会切换我猜是从 .png 到 .tiff。

问题似乎是,NSImage 确实 not 有一个类似于 UIImage 的 init(named:in:compatibleWith:) 的初始化程序,它可以让您指定 bundle 从加载图像(第二个参数)。

您可以改为要求特定的捆绑包(main 除外)创建资源 URL 并从中实例化图像(就像我在上面所做的那样),但这似乎与资产目录不兼容。 欢迎提供更多信息...

【问题讨论】:

    标签: macos nsimage asset-catalog xctestcase


    【解决方案1】:

    Bundle 上有一个扩展,允许从资产目录加载命名图像:

    extension Bundle {
        @available(OSX 10.7, *)
        open func image(forResource name: NSImage.Name) -> NSImage?
    }
    

    参考您的示例,您可以在 XCTestCase 中使用以下内容来访问图像(Swift 5):

    guard let image = Bundle(for: type(of: self)).image(forResource: "TestSourceImage") else {
        fatalError("Test Resource is Missing.")
    }
    

    在 macOS 10.14 上测试。

    【讨论】:

    • 谢谢,它有效!已经有一段时间了,我目前没有从事那个项目(尽管它并没有完全被放弃),所以我不得不做一些搜索来找到它并尝试你的解决方案:-)
    猜你喜欢
    • 2017-05-05
    • 1970-01-01
    • 1970-01-01
    • 2016-12-22
    • 1970-01-01
    • 1970-01-01
    • 2014-08-14
    • 2022-12-22
    • 2013-10-29
    相关资源
    最近更新 更多