Testing for ODR image resources in main bundle

49 views Asked by At

I'm trying to write a test to make sure all ODR images are available in the main bundle:

let testBundle = Bundle(for: type(of: self)) //This is probably wrong... I'm trying to test the main bundle.

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)
   // let fileUrl = Bundle.main.url(forResource: fileNameWithoutExtension, withExtension: fileExtension) // also doesn't work
    XCTAssertNotNil(fileUrl, "File \(cat.image) is not available as an ODR resource.")
}

cat.image could be "filename.jpg" or "filename.png" for example.

But this test fails for every image, even those that I'm sure are present in the bundle. What am I doing wrong?

1

There are 1 answers

3
Robson Novato On

Probably the best way to do this is to try to convert the name of all the images you created to a UIImage, if you can all the Assets are imported correctly.

I added cat 1, 2 and 3 in assets and made this code for testing if they exist:

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.")
    }
}

If there are any nuances that I didn't notice, let me know ;)