XCUITest Reading file from bundle form UITest target

Viewed 282

I am trying to read a plist file present in Xcode bundle,

Approach #1 (Didn't work): I was using a static variable(Line #23 in below screenshot) which returns the path of file present in bundle, It didn't work Nonworking1

Approach #2 (Didn't work): Using Bundle.main to read a file didn't work Notworking2

Approach #3 (Working solution): When I write a function (Line #30 in below screenshot) with same lines of code, It works! working

Initially I was trying to read file using the static variable and wasted 2 days, until I figured out that using function instead of static variable would work.

Questions:

  1. I cant find any relevant documentation, Can anyone explain why this Approach #1 didn't work?
  2. Is the type(of:) specific for object type not class type?
1 Answers

The correct way to read file from within UITest target is

Correct way to read file:

func getPath() -> String?  {
    let bundle = Bundle(for: type(of: self))
    let path = bundle.path(forResource: "MockMDM", ofType: "plist")
    return path
}

Also let me share the code which seem correct but wont work

Wrong way to read file:

static var mockMDMFile: [String: Any]? {
    
    if let path = Bundle.main.path(forResource: "MockMDM", ofType: "plist") {
        let mdmDict = NSDictionary(contentsOfFile: path) as! [String: Any]
        return mdmDict
    }
    return nil
}

Reason for failure of wrong way:

  • App has multiple bundles, and the files present in the UITest target will be part of a different bundle NOT Main bundle (Bundle.main).
Related