【问题标题】:Reading Info.plist from UITests in iOS?从 iOS 的 UITests 中读取 Info.plist?
【发布时间】:2026-02-10 04:30:01
【问题描述】:

是否可以在 UITesting 时从 UITests 文件夹文件中的 Info.plist 文件中读取?如果是这样,如何。

到目前为止,我已经尝试过:

if let url =  Bundle.main.url(forResource: "Info", withExtension: "plist"),
        let myDict = NSDictionary(contentsOf: url) as? [String:Any] {
        print(myDict)
    }

不过,这会返回一些plist,这不是我在主项目文件夹中拥有的那个。

【问题讨论】:

    标签: ios swift ui-testing


    【解决方案1】:

    您需要阅读(或注入)您的测试类的特殊捆绑包。试试这个。将下面 Bundle(for:) 调用中的 OSTests 替换为您的 XCTestCase 子类的名称。

      func testExample() {
        let testBundle = Bundle(for: OSTests.self)
        if let url = testBundle.url(forResource: "Info", withExtension: "plist"),
          let myDict = NSDictionary(contentsOf: url) as? [String:Any] {
          print(myDict)
        }
      }
    

    然后,您需要确保将测试包复制到您的测试应用中。选择您的测试目标。公开 Build Phases 选项卡中的 Copy Bundle Resources 部分。单击 + 图标并选择您的测试目标的 Info.plist 文件。

    这是我当时的结果。

    【讨论】: