Xcode - 将图像添加到测试中?

Jen*_*ars 7 xcode ios swift

我正在为Swift应用程序编写测试.在此期间我需要测试处理图像.我想添加一个示例图像进行测试.根据我的理解,这似乎是错误的,我应该能够将图像直接拖到Xcode的ProductNameTests目录中.这会将图像添加到测试目标中.然后我尝试获取图像的路径:

let imagePath = NSBundle.mainBundle().pathForResource("example_image", ofType: "jpg")
Run Code Online (Sandbox Code Playgroud)

不幸的是,这总是回归nil.我究竟做错了什么?谢谢!

Chr*_*örz 5

您的问题是,您在主包中搜索图像.因此,您现在可以访问mainBundle图像不存在的位置,因为它位于测试包中.

所以你需要访问另一个包.嵌套测试类的包.

为此,请使用bundleForClass而不是mainBundle:

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

如您所见,您加载了NSBundle您的课程,您现在应该可以访问该图像.您还可以将图像添加到主目标并mainBundle再次使用.