首页 > 解决方案 > IOS测试与Mac文件系统交互

问题描述

所以我在玩 swiftui XCTestCase。我有一堆测试运行并得到它们在模拟器或设备上运行。

但是 - 我现在需要与我正在使用的 Mac 进行交互 - 即从 IOS 测试读取和写入 Mac 文件系统 - 是否有可能 - 因为测试在模拟器中运行。

标签: iosswifttestingxctestcase

解决方案


XCTestCase可以访问本地文件系统被设计有一些限制。例如:

func testExample() throws {
    print("\(Bundle.allBundles)")
    print("\(Bundle(for: type(of: self)))")
}

此代码将产生如下内容:

[NSBundle </Volumes/Extended/Archive/Xcode_11.6.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/CoreServices/CoreGlyphs.bundle> (not yet loaded), NSBundle </Users/dive/Library/Developer/CoreSimulator/Devices/9CDF771B-204F-45B9-AAC3-6036AB7B117D/data/Containers/Bundle/Application/5DE85255-F202-4BAB-871A-7C20C2DB37D9/TestingBundles.app> (loaded), NSBundle </Users/dive/Library/Developer/CoreSimulator/Devices/9CDF771B-204F-45B9-AAC3-6036AB7B117D/data/Containers/Bundle/Application/5DE85255-F202-4BAB-871A-7C20C2DB37D9/TestingBundles.app/Frameworks> (not yet loaded), NSBundle </Users/dive/Library/Developer/Xcode/DerivedData/TestingBundles-exdmnsfatmhbztarzgjvvlwwpoan/Build/Products/Debug-iphonesimulator/TestingBundles.app/PlugIns/TestingBundlesTests.xctest> (loaded)]

NSBundle </Users/dive/Library/Developer/Xcode/DerivedData/TestingBundles-exdmnsfatmhbztarzgjvvlwwpoan/Build/Products/Debug-iphonesimulator/TestingBundles.app/PlugIns/TestingBundlesTests.xctest> (loaded)

如您所见,这些路径与 DerivedData 目录相关。因此,您不能在项目或测试中使用目录的相对路径。

此外,您可以FileManager直接使用。它继承了相同的环境并且也可以访问本地文件系统。例如:

func testExample() throws {
    let manager = FileManager.default
    print(try manager.contentsOfDirectory(atPath: ("~/" as NSString).expandingTildeInPath))
}

它会产生这样的东西:

/Users/USER_NAME/Library/Developer/CoreSimulator/Devices/9CDF771B-204F-45B9-AAC3-6036AB7B117D/data/Containers/Data/Application/0D16C376-80A6-4DAE-B435-2FEF7F08A83A

请注意,由于环境原因,它指向模拟器中用户的主目录。

作为一种解决方法,我们使用共享用户目录来共享此类数据。测试前操作中有一个“运行脚本”可以复制它:

在此处输入图像描述

然后我们像这样访问它XCTestCase

try manager.contentsOfDirectory(atPath: "/Users/Shared/TestData")

这并不理想,也许还有其他一些解决方案。但它工作正常并且具有可预测的行为。


推荐阅读