如何在TestCase中快速加载文件

hap*_*497 3 swift

在我的 swift 项目的 Tests 目录中,我有一个测试用例目录和一个测试文件目录。

+ Tests
   + UnitTest
       + MySwiftTests.swift
   + SourceFiles
       + file1.xml
Run Code Online (Sandbox Code Playgroud)

我需要创建一个 FileManager 来在 MySwiftTests 中加载“file1.xml”。我的问题是如何在与测试用例相关的 FileManager 的 url 中指定 SearchPathDirectory 和 SearchPathDomainMask?

func url(for: FileManager.SearchPathDirectory, in: FileManager.SearchPathDomainMask,propertyFor: URL?, create: Bool) -> URL

https://developer.apple.com/documentation/foundation/filemanager

Dan*_*arx 5

let bundle = Bundle(for: type(of: self))
guard let path = bundle.path(forResource: "file1", ofType: "xml") else {
    // File not found ... oops
    return 
}
// Now you can access the file using e.g. String(contentsOfFile:)
let string = try? String(contentsOfFile: path)
// or Data? using the FileManager
let data = FileManager.default.contents(atPath: path)
Run Code Online (Sandbox Code Playgroud)

确保将 file1.xml 添加到您的测试目标