7

I am trying to read .json file in my unit test and running it within Swift Package. Using Xcode 11 and Swift 5.1

let path = Bundle.main.url(forResource: filename, withExtension: "json")
// Path is nil

I've been told that Swift packages don't have bundles any more. So how can I workaround this?

Part of my Swift.package

.testTarget(
    name: "ProjectTests", 
    dependencies: [
        .target(name: "Project")
    ],
    path: "Tests",
    exclude: [
        "Folder/File.swift"
    ]
)

1 Answer 1

4

The solution we have found is FileManager.

var cache: [String: URL] = [:] // Save all local files in this cache
let baseURL = urlForRestServicesTestsDir()

guard let enumerator = FileManager.default.enumerator(
    at: baseURL,
    includingPropertiesForKeys: [.nameKey],
    options: [.skipsHiddenFiles, .skipsPackageDescendants], 
    errorHandler: nil) else {
        fatalError("Could not enumerate \(baseURL)")
}

for case let url as URL in enumerator where url.isFileURL {
    cache[url.lastPathComponent] = url
}

You will need this method

static func urlForRestServicesTestsDir() -> URL {
    let currentFileURL = URL(fileURLWithPath: "\(#file)", isDirectory: false)
    return currentFileURL
        .deletingLastPathComponent()
        .deletingLastPathComponent()
}

After this you can get URL for every file:

func url(for fileName: String) -> URL? {
    return cache[fileName]
}

In case you will only want to run this code in Swift package use #if SWIFT_PACKAGE.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.