Swift 4+
I found none of the answers here up–to date or using a URL.
First add the following function to your testClass:
/// getFile. Opens a file in the current bundle and return as data
/// - Parameters:
/// - name: fileName
/// - withExtension: extension name, i.e. "json"
/// - Returns: Data of the contents of the file on nil if not found
static func getFile(_ name: String, withExtension: String) -> Data? {
guard let url = Bundle(for: Self.self)
.url(forResource: name, withExtension: withExtension) else { return nil }
guard let data = try? Data(contentsOf: url) else { return nil }
return data
}
Then you can call it in your test class like this:
func test() throws {
let xmlData = Self.getFile("TestData", withExtension: "xml")
XCTAssertNotNil(xmlData, "File not found")
}
Note: Apple recommends that URL's should always be used for resources (not paths) for security reasons.