【问题标题】:Xcode - Adding an image to a test?Xcode - 将图像添加到测试中?
【发布时间】:2015-02-04 18:15:20
【问题描述】:

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

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

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

【问题讨论】:

  • 您是否将图像添加到测试目标?如果您选择图像并查看检查器面板,您应该在 <ProjectName>-tests 目标旁边有一个勾号。

标签: ios xcode swift


【解决方案1】:

您的问题是,您在主包中搜索图像。因此,目前您访问了您的图像不存在的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

【讨论】:

    【解决方案2】:

    在 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")
    

    【讨论】:

      【解决方案3】:

      在 Swift 4 中你可以这样做

      let testImage = UIImage(named: <#Image Name String#>, in: Bundle(for:<#Class Name#>.self), compatibleWith: nil)
      

      这是从我的 xcassest 中为我获取的图像,它是我的测试目标和主要目标的一部分

      我在 setUp() 函数中使用它来传递给我需要测试的图像处理类

      【讨论】:

        【解决方案4】:

        无法使用 Images.xcassets。在这种特殊情况下,您需要在 XCode 中创建组(文件夹),并将图像添加到文件夹中(确保通过单击“如果需要复制项目”将图像复制到 Copy Bundle Resources)。然后:

        Swift 5.x:

        let path = Bundle(for: type(of: self)).path(forResource: "TestingImage", ofType: "jpg")
        

        并确保将图像检入到测试目标中。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-09-22
          • 2023-03-28
          • 2020-08-13
          • 1970-01-01
          • 2018-02-05
          • 2012-06-15
          • 2014-11-17
          • 2014-09-15
          相关资源
          最近更新 更多