首页 > 解决方案 > 如何快速加载TestCase中的文件

问题描述

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

+ Tests
   + UnitTest
       + MySwiftTests.swift
   + SourceFiles
       + file1.xml

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

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

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

标签: swift

解决方案


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)

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


推荐阅读