Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xcode - Adding an image to a test?

Tags:

xcode

ios

swift

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

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

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

like image 288
Jenny Shoars Avatar asked Feb 04 '15 18:02

Jenny Shoars


People also ask

How do I add an image to Xcode?

Drag and drop image onto Xcode's assets catalog. Or, click on a plus button at the very bottom of the Assets navigator view and then select “New Image Set”. After that, drag and drop an image into the newly create Image Set, placing it at appropriate 1x, 2x or 3x slot.

How do I add test cases in Xcode?

The easiest way to add a unit test target to your project is to select the Include Tests checkbox when you create the project. Selecting the checkbox creates targets for unit tests and UI tests. To add a unit test target to an existing Xcode project, choose File > New > Target.


1 Answers

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.

like image 102
Christian Avatar answered Sep 29 '22 19:09

Christian