似乎在使用 Swift Package Manager ( swift test
) 运行测试时,工作目录是项目的根目录。这允许使用相对路径(例如。./Tests/Resources
)轻松地从磁盘加载资源。
在评估了不同的选项之后,我编写了以下类来从测试包(如果可用)或给定路径中检索路径。
class Resource {
static var resourcePath = "./Tests/Resources"
let name: String
let type: String
init(name: String, type: String) {
self.name = name
self.type = type
}
var path: String {
guard let path: String = Bundle(for: Swift.type(of: self)).path(forResource: name, ofType: type) else {
let filename: String = type.isEmpty ? name : "\(name).\(type)"
return "\(Resource.resourcePath)/\(filename)"
}
return path
}
}
资源必须添加到所有测试目标才能在捆绑包中可用。例如,可以通过文件扩展名更新上述类以支持多个资源路径。
然后可以XCTest
根据需要从 a 加载资源:
let file = Resource(name: "datafile", type: "csv")
let content = try String(contentsOfFile: file)
let image = try UIImage(contentsOfFile: Resource(name: "image", type: "png"))
可以添加扩展Resource
以加载不同格式的内容。
extension Resource {
var content: String? {
return try? String(contentsOfFile: path).trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
}
var base64EncodedData: Data? {
guard let string = content, let data = Data(base64Encoded: string) else {
return nil
}
return data
}
var image: Image? {
return try? UIImage(contentsOfFile: path)
}
}
并用作:
let json = Resource(name: "datafile", type: "json").contents
let image = Resource(name: "image", type: "jpeg").image