hap497
hap497

Reputation: 162915

How to load files in TestCase in swift

In my Tests directory in my swift project, I have a directory for test cases and a directory for test files.

+ Tests
   + UnitTest
       + MySwiftTests.swift
   + SourceFiles
       + file1.xml

I need to create a FileManager to load 'file1.xml' in my MySwiftTests. My question is how to specify the SearchPathDirectory and SearchPathDomainMask in the url of the FileManager which is relative the the test cases?

func url(for: FileManager.SearchPathDirectory, in: FileManager.SearchPathDomainMask, appropriateFor: URL?, create: Bool) -> URL

https://developer.apple.com/documentation/foundation/filemanager

Upvotes: 4

Views: 1720

Answers (1)

Daniel Marx
Daniel Marx

Reputation: 764

let bundle = Bundle(for: type(of: self))
guard let path = bundle.path(forResource: "file1", ofType: "xml") else {
    // File not found ... oops
    return 
}
// Now you can access the file using e.g. String(contentsOfFile:)
let string = try? String(contentsOfFile: path)
// or Data? using the FileManager
let data = FileManager.default.contents(atPath: path)

Make sure to add file1.xml to your Test Target

Upvotes: 5

Related Questions