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!
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With