Xamarin.UITest测试时copyItemAtPath提示源文件不存在但实际存在如何解决
结论
你的判断完全正确,该异常本质是目标路径的Caches文件夹不存在导致,报错提示的「源文件不存在」属于系统错误描述的误导。
原因分析
NSCocoaErrorDomain Code=4错误实际覆盖两种触发场景:源文件不存在、目标文件的父级目录不存在。你已经通过终端验证源文件真实存在,且目标路径的Caches目录确实不存在,完全匹配第二种触发场景。- 全新安装的iOS应用沙盒中,系统不会默认创建
Library/Caches目录,只有当应用首次主动向Caches目录写入内容时才需要开发者手动创建该目录。 - 此前逻辑未触发异常是因为旧运行环境中,该段代码执行前已经有其他业务逻辑先创建了Caches目录;而Xamarin.UITest运行时会每次清空应用沙盒、模拟全新安装状态,没有前置逻辑创建Caches目录,因此触发问题。
修复方案
在复制文件前先判断Caches目录是否存在,不存在则主动创建,修改后的代码示例:
NSString * cachesDir = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject]; NSFileManager * defaultFileManager = [NSFileManager defaultManager]; // 先判断Caches目录是否存在,不存在则创建 if (![defaultFileManager fileExistsAtPath:cachesDir]) { [defaultFileManager createDirectoryAtPath:cachesDir withIntermediateDirectories:YES attributes:nil error:nil]; } NSString * configurationCachePath = [cachesDir stringByAppendingPathComponent: @"config.json"]; NSString * configurationBundlePath = [[NSBundle mainBundle] pathForResource: @"config" ofType: @"json"]; NSError * error = NULL; if (![defaultFileManager fileExistsAtPath: configurationCachePath]) { if (!configurationBundlePath || ![defaultFileManager copyItemAtPath: configurationBundlePath toPath: configurationCachePath error: &error]) { LogConfig(@"Could not copy configuration file from path : %@ to path : %@ - error : %@", configurationBundlePath, configurationCachePath, error); } }
内容的提问来源于stack exchange,提问作者LiohAu
相关产品推荐
相关产品推荐

