ios - Xcode 在单元测试中写入文件

标签 ios xcode unit-testing swift

我理解单元测试执行时,是在Xcode的沙盒环境中。 在单元测试中,我需要将数据写入和读取文件。 由于该项目驻留在 git 存储库中,因此必须完全从代码中完成(即不可能对目录进行特殊的手动测试设置)

在我今天的所有搜索和尝试中,我找不到从单元测试中写入文件的方法。

有人知道在这些条件下写入文件的方法吗?

编辑:这是有问题的代码:

let dirPath = NSTemporaryDirectory()!

var filePath = dirPath.stringByAppendingPathComponent("unittest.json")

if !NSFileManager.defaultManager().isWritableFileAtPath(filePath) {
    return (nil, "Directory missing or write access not granted for \(path)")
}

最佳答案

您应该能够使用临时目录:NSTemporaryDirectory() 并让它可靠地指向一个安全的读写位置。我建议您确保清理所有创建的文件。

let dirPath = NSTemporaryDirectory()

要查看是否可以创建文件(根据更新的问题),请检查目录的写入权限:

let canCreate = NSFileManager.defaultManager().isWritableFileAtPath(dirPath)

关于ios - Xcode 在单元测试中写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28030011/

相关文章:

ios - 如何在 Swift 中的字符串中的特定索引处添加字符

xcode - 什么是编译C?

javascript - 在 sinon 中 stub 整个类以进行测试

ios - ID 为 :[. ..] 的 NSManagedObject 已失效

ios - Oleb 文档上的 CAFilter 是什么

objective-c - 删除UIView底部的灰色条

Xcode:malloc_error_break 上的自动(永久)断点?

javascript - QUnit : One test per method with multiple assertions or multiple tests per method?

java - 我如何在 Android 中使用 JUnit 测试模型?

ios - 如何将 UITableView Wrapper 的大小调整为与 UITableView 相同的大小?