首页 > 解决方案 > 为 Xcode SPM 测试复制资源文件

问题描述

我是 Swift 包管理器的新手,但它已集成到 Xcode 11 中,是时候尝试一下了。我在新工作区中有一个新的应用程序和 SPM 库。我有一个带有测试的工作库,并且已成功将该库导入到应用程序中。

我需要使用解析 json 文件的新测试来扩展 SPM 库。我了解到不支持资源目录功能。唯一可行的方案似乎是将文件复制步骤添加到库构建过程中,以便可执行文件可以发现资源文件。

我可以从命令行弄清楚如何做到这一点,但不能通过 Xcode 运行构建和测试。没有复制捆绑资源,快速包的构建阶段。事实上,一切似乎都被 Xcode 隐藏了。

我在 SPM 中查看了 Makefile 类型的文件,这些文件允许我编辑默认命令行操作,从而绕过 Xcode;但我没有看到他们。

是否有某种方法可以交互/控制 Xcode 11 如何构建 SPM 目标,以便我可以将非代码文件复制到测试目标?

标签: xcode11swift-package-manager

解决方案


搞定了!!!

struct Resource {
  let name: String
  let type: String
  let url: URL

  init(name: String, type: String, sourceFile: StaticString = #file) throws {
    self.name = name
    self.type = type

    // The following assumes that your test source files are all in the same directory, and the resources are one directory down and over
    // <Some folder>
    //  - Resources
    //      - <resource files>
    //  - <Some test source folder>
    //      - <test case files>
    let testCaseURL = URL(fileURLWithPath: "\(sourceFile)", isDirectory: false)
    let testsFolderURL = testCaseURL.deletingLastPathComponent()
    let resourcesFolderURL = testsFolderURL.deletingLastPathComponent().appendingPathComponent("Resources", isDirectory: true)
    self.url = resourcesFolderURL.appendingPathComponent("\(name).\(type)", isDirectory: false)
  }
}

用法:

final class SPMTestDataTests: XCTestCase {
  func testExample() throws {
    // This is an example of a functional test case.
    // Use XCTAssert and related functions to verify your tests produce the correct
    // results.
    XCTAssertEqual(SPMTestData().text, "Hello, World!")

    let file = try Resource(name: "image", type: "png")
    let image = UIImage(contentsOfFile: file.url.path)
    print(image)
  }
}

在此处输入图像描述

我在#file 这里找到了使用的关键


推荐阅读