App resources not available when UI testing in Xcode 7
Asked Answered
P

2

6

I'm trying to extend the new UI testing functionality in Xcode 7 by snapshotting the current screen elements (labels, images, buttons) and saving their accessibility information to json files.

The idea is that when running the UI tests later, a current screen snapshot can be taken and compared to the existing one, the test will fail if additional or missing elements are found.

Unfortunately the app resources don't seem available during UI testing, even with the correct target, so the json files can't be loaded for comparison. The following standard code fails to load a resource:

guard let resourcePath = NSBundle.mainBundle ().pathForResource ("StartScreenShapshot", ofType:"json") else {
        XCTFail ("can't load resource StartScreenShapshot")
        return
    }

I can understand why Apple have taken this sandbox approach, as UI testing should be based on what's happening on the screen, and access to the workings of app shouldn't be needed, but not having access to the resource bundle is a pain.

So is there a way to load local resources from the app, or some other way locally, during Xcode 7 UI testing?

Saving the files locally (automatically) would also be a huge plus, would save creating them manually.

Pasty answered 11/9, 2015 at 11:30 Comment(2)
seems you faced old problem with tests and bundles, if so look at this question https://mcmap.net/q/240117/-nsurl-to-file-path-in-test-bundle-with-xctestAdvertent
Thanks man, this was the issue. Have posted an answer, cheers.Pasty
P
6

Thanks to @sage444

For unit testing the mainBundle() method doesn't work for retrieving a resource path, using a class does.

 guard let resourcePath = NSBundle (forClass: self.dynamicType).pathForResource (contentName, ofType:"json") else {
        XCTFail ("can't load resource \(contentName)")
        return
    }
Pasty answered 11/9, 2015 at 14:2 Comment(0)
K
2

Thanks @danfordham

Updated for Swift 3

1) Copy bundle resources enter image description here

2) Reference new bundle this way,

guard let path = Bundle(for: type(of: self)).path(forResource: contentName, ofType: "json") else {
    XCTFail ("can't load resource \(contentName)")
    return
}
Kattegat answered 10/5, 2017 at 18:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.