Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load files in TestCase in swift

Tags:

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

like image 505
hap497 Avatar asked Aug 31 '25 15:08

hap497


1 Answers

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

like image 69
Daniel Marx Avatar answered Sep 03 '25 12:09

Daniel Marx