3

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

hap497
  • 154,439
  • 43
  • 83
  • 99
  • Why FileManager? Why not just Bundle? Because your files are in your Bundle. `let url = Bundle(for: type(of: self)).url(forResource: "file1", withExtension: "xml")` (just used it yesterday, and `Bundle.main` is the bundle of the hosting app, and so was failing). – Larme Jul 22 '20 at 07:27
  • Does this answer your question? [Accessing Bundle of main application while running XCTests](https://stackoverflow.com/questions/48301370/accessing-bundle-of-main-application-while-running-xctests) – Larme Jul 22 '20 at 08:25

1 Answers1

5
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

Daniel Marx
  • 676
  • 5
  • 8
  • I have dragged my files to Xcode project and I 'add the them to the test target in the pop up window'. But when I run the code. I get error `Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)` that is in this line ` let path = bundle.url(forResource: "file1", withExtension: "xml")! – hap497 Jul 23 '20 at 02:49
  • just saw a copy paste error but don't know if it's linked to your Exception. I edited my answer to retrieve the path using: `let path = bundle.path(forResource: "file1", ofType: "xml")!` and as I stated forced unwrap is not recommended. To make sure you won't trigger an exception you might wanna add a guard. – Daniel Marx Jul 23 '20 at 05:54
  • if the file is still not found you might wann check the bundle resources: **->** Select project in the Project Navigator **->** Select Test Target in the TARGETS list **->** Go to Build Phases **->** expand Copy Bundle Resources entry **->** there the depending files should be listed **->** if not you can still add them manually – Daniel Marx Jul 23 '20 at 06:05