You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 12:24:04