swift - 如何快速加载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
解决方案
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 添加到您的测试目标
推荐阅读
- php - 在从帖子标题共享预览和通知标题中使用 Shorcodes
- python - 将网页中的表格元素存储在字典中
- c# - 由于索引问题,无法创建 Fluent API 外键
- android-emulator - 如何编辑模型和硬件模拟器
- android - Android - 打印时可以设置份数
- selenium-webdriver - 我正在尝试在 selenium webdriver 中上传文件,因为 selenium 正在选择要上传的文件,但无法单击上传按钮
- vba - 通过 iCalendar 转发信息减少的约会
- flutter - 未找到使用颤振中的mailto链接处理意图错误的活动
- java - 需要加快条件复制属性操作
- python - 如何从 s3 存储桶在 lambda 函数中输入 ttf 文件?