测试主包中的 ODR 图像资源

问题描述 投票:0回答:1

我正在尝试编写一个测试,以确保所有 ODR 图像都在主包中可用:

let testBundle = Bundle(for: type(of: self))

for cat in cats {
    let fileURL = URL(fileURLWithPath: cat.image)
    let fileNameWithoutExtension = fileURL.deletingPathExtension().lastPathComponent
    let fileExtension = fileURL.pathExtension
    let fileUrl = testBundle.url(forResource: fileNameWithoutExtension, withExtension: fileExtension)
    XCTAssertNotNil(fileUrl, "File \(cat.image) is not available as an ODR resource.")
}
例如,

cat.image
可以是“filename.jpg”或“filename.png”。

但是这个测试对于每张图像都失败了,即使是那些我确信捆绑包中存在的图像。我做错了什么?

swift bundle xctest xctestcase
1个回答
0
投票

可能最好的方法是尝试将您创建的所有图像的名称转换为 UIImage,如果可以正确导入所有资源。

我在资产中添加了cat 1、2和3,并编写了此代码来测试它们是否存在:

let testBundle = Bundle(for: pergunta_stackTests.self)

let cats: [Cats] = [Cats(name: "James", image: "cat1.jpeg"),
Cats(name: "Luke", image: "cat2.jpeg"),
Cats(name: "Amir", image: "cat3.jpeg")]

func testIfCatsExist() {
    for cat in cats {
        let fileURL = URL(fileURLWithPath: cat.image)
        let fileNameWithoutExtension = fileURL.deletingPathExtension().lastPathComponent
        let imageCreate = UIImage(named: fileNameWithoutExtension)
        XCTAssertNotNil(imageCreate, "File \(cat.image) is not available as an ODR resource.")
    }
}

如果有任何我没有注意到的细微差别,请告诉我;)

© www.soinside.com 2019 - 2024. All rights reserved.