我的UITests目标中有一个示例文本文件。我想将此文件复制到应用程序的documents目录中,以便在对应用程序中的文件上传进行测试时,可以通过“文件”应用程序将其选中并上传。
最佳答案
这可以通过使用XCUIApplication的launchArguments来实现。它需要在应用程序的plist中包含以下键:LSSupportsOpeningDocumentsInPlace
和UIFileSharingEnabled
或UISupportsDocumentBrowser
。
// File: FileUploadUITests.swift
// Target: UITests
func launchApplication() {
let fileName = "__File_12345678910.txt"
let app = XCUIApplication()
app.launchArguments.append("-fileUrlPath")
app.launchArguments.append(sampleTextFileURL().path)
app.launchArguments.append("-fileName")
app.launchArguments.append(fileName)
app.launch()
}
func sampleTextFileURL() -> URL {
let bundle = Bundle(for: FileUploadUITests.self)
return bundle.url(forResource: "text_file_example", withExtension: "txt")!
}
// File: TestHelper.swift
// Target: App
@discardableResult
func processArgumentsForTesting() -> Bool {
if let index = ProcessInfo.processInfo.arguments.index(where: { $0 == "-fileUrlPath" }) {
let path = ProcessInfo.processInfo.arguments[index + 1]
let url = URL(string: path)!
let fileName: String?
if let index = ProcessInfo.processInfo.arguments.index(where: { $0 == "-fileName" }) {
fileName = ProcessInfo.processInfo.arguments[index + 1]
} else {
fileName = nil
}
copyTestFileToDocumentDirectory(url: url, fileName: fileName)
return true
}
return false
}
private let fileManager = FileManager.default
private var documentDirectoryURLOfTheApp: URL {
let paths = fileManager.urls(for: .documentDirectory, in: .allDomainsMask)
let documentDirectoryPath = paths.first!
return documentDirectoryPath
}
@discardableResult
private func copyTestFileToDocumentDirectory(url: URL, fileName: String? = nil) -> Bool {
let directory = documentDirectoryURLOfTheApp
let destination = directory.appendingPathComponent(fileName ?? url.lastPathComponent).path
let isOkay: Bool
do {
if fileManager.fileExists(atPath: destination) {
try fileManager.removeItem(atPath: destination)
}
try fileManager.copyItem(atPath: url.path, toPath: destination)
isOkay = true
} catch {
isOkay = false
}
return isOkay
}
// File: AppDelegate.swift
// Target: App
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
processArgumentsForTesting()
return true
}
关于ios - 是否可以将UITests目标中的文件复制到应用程序的documents目录?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58600990/