Xcode - adding image to test?

I am currently writing tests for a Swift application. During which I need to test image processing. I would like to add an example image for testing. From my understanding, which seems wrong, I should just drag the image directly into the Xcode ProductNameTests directory. This adds an image to the purpose of the tests. Then I try to get the path to the image as such:

let imagePath = NSBundle.mainBundle().pathForResource("example_image", ofType: "jpg")

This, unfortunately, always returns nil. What am I doing wrong? Thank!

+4
source share
2 answers

, . mainBundle, , .

, . , .

bundleForClass mainBundle:

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

, NSBundle , . mainBundle.

+3

Swift 3 :

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
}

:

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

All Articles