如何在Xcode UITest Target中正确使用info.plist?
UITest Target中info.plist的正确使用与字段获取
- UITest Target完全支持使用info.plist配置自定义字段,问题核心是不能用
Bundle.main获取UITest自身的配置。 - 原因:UITest是独立于主App的测试进程,
Bundle.main指向的是被测试的主应用Bundle,而非UITest Target自己的Bundle,因此无法读取UITest的info.plist内容。
正确获取UITest Bundle的方式
方式1:通过测试类的类型获取(推荐)
利用当前测试类属于UITest Target的特性,直接获取对应Bundle:
let testBundle = Bundle(for: type(of: self)) if let email = testBundle.object(forInfoDictionaryKey: "EMAIL") as? String { // 使用email字段 }
这种方式无需硬编码Bundle ID,适配性更强。
方式2:通过Bundle ID直接获取
若明确UITest Target的Bundle ID,可直接初始化:
guard let testBundle = Bundle(identifier: "com.yourcompany.YourAppUITests") else { fatalError("UITest Bundle not found") } let email = testBundle.object(forInfoDictionaryKey: "EMAIL") as? String
关于Xcode 13+的info.plist自动生成
不管是Xcode默认的自动生成模式(仅包含自定义字段的独立plist),还是关闭自动生成后的完整plist,只要自定义字段正确添加到UITest Target的info.plist中,使用上述正确的Bundle就能正常读取,和plist的生成方式无关。
你之前遍历Bundle.allBundles能找到目标Bundle,本质就是定位到了UITest自身的Bundle,而上面的两种方式是更精准、高效的获取方式,无需遍历所有Bundle。
内容的提问来源于stack exchange,提问作者General Failure
相关产品推荐
相关产品推荐

