Xcode - Adding an image to a test?

Your problem is, that you search for the image in the main bundle. So at the moment you access the mainBundle where your image doesn't exists, because it's in the test-bundle.

So you need to access another bundle. The bundle where your testclass is nested.

For that, use bundleForClass instead of mainBundle:

//The Bundle for your current class
var bundle = NSBundle(forClass: self.dynamicType)
var path = bundle.pathForResource("example_image", ofType: "jpg")

As you see, you load the NSBundle for your class and you should now be able to access the image. You could also add the image to your main target and use the mainBundle again.


In Swift 3, I'm using this method to load an image in test:

func loadImage(named name: String, type:String = "png") throws -> UIImage {
    let bundle = Bundle(for:type(of:self))
    guard let path = bundle.path(forResource: name, ofType: type) else {
        throw NSError(domain: "loadImage", code: 1, userInfo: nil)
    }
    guard let image = UIImage(contentsOfFile: path) else {
        throw NSError(domain: "loadImage", code: 2, userInfo: nil)
    }
    return image
}

And then I use in test:

let image = try loadImage(named:"test_image", type: "jpg")

Tags:

Ios

Xcode

Swift