LoginSignup
2
1

More than 3 years have passed since last update.

XCUITestからplistを参照する

Last updated at Posted at 2020-02-26

UITest実行時は少し参照方法が違うようです。
Bundleが違うということですね。

Bundle.main.path(forResource: "Info", ofType: "plist")とにらめっこしてましたが

例として、ファイルツリーのhogeUITest以下にInfo.plistを配置し、
XCTestCaseから参照する場合は以下の通りです。

let testBundle = Bundle(for: type(of: self))
if let filePath = testBundle.path(forResource: "Info", ofType: "plist") {
    if let dict = NSDictionary(contentsOfFile: filePath) {
        if let value = dict["key"] as? String {
            print(value)
        }
    }
}

トラブルシューティング

目的のkeyが見つからないときは、想定しているplistか疑う必要があります。
XCTestCaseから呼ぶ場合はBundle(for: type(of: self))でOKですが、
テストファイルの中ではなく、通常のアプリ内のクラスに実装すると、当然selfではなくなるので注意です。

困ったときはbundleBundle.allBundlesとして探してみてください。
[bundle]でとれるのでまわして探しても見つからないか確認しましょう。

闇実装

.allBundlesというのを見つけました。Test側もそうじゃない方からも探せます。

let bundles: [Bundle] = Bundle.allBundles
for bundle in bundles {
    if let filePath = bundle.path(forResource: "Info", ofType: "plist") {
        if let dict = NSDictionary(contentsOfFile: filePath) {
            if let value = dict["key"] as? String {
                print("みつけた!")
            }
        }
    }
}
2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1