Loading resources for use with unit tests in a Swift package does not appear to be a simple task. Apple's article Bundling Resources with a Swift Package recommends using Bundle.module
but Bundle does not include a definition of this property. It is actually generated when using SPM with a target which defines resources. Using it means other build systems such as Xcode projects and CocoaPods cannot be used once Bundle.module
is used.
An alternative to getting the path is to use #file
to implement a findUp
function which will look for the root directory. From there it will append Resources
which is where all resources will be located. It is not necessary to declare them as a part of the package since this is just for unit tests when the source will be available when tests are run.
The tests find, load and decode the sample resource with supporting functions and a lazy property. This way JSON resources which can be loaded with Codable
can be used by tests without updating Package.swift
with a list of resources.