How to add JSON for UnitTest in SPM?
Recently, I was developing a wrapper for a Rick and Morty API, and when it came to writing tests, I found an interesting challenge: How do I add my JSON files to make my stubs?
Well, it is actually very easy and consists of doing the following:
targets: [
.target(
name: "RickAndMortyAPI",
dependencies: []),
.testTarget(
name: "RickAndMortyAPITests",
dependencies: ["RickAndMortyAPI"],
resources: [
// Here we specify where our JSONs will reside
.process("Resources")
]),
]
As we can see in our targets section—in my case, the test target—we add the resources attribute, where we specify the path where our JSONs will be located using the static function process. In this function, we pass the directory name Resources, which we need to create in our project structure:

What I would like to clarify is that we must respect the name we add in package.swift in both the manifest and the folder structure. If they are different, it will not work.
At first, this caused me a bit of confusion. When developing for iOS, if you change the file name in the folder structure, it doesn’t strictly match the class name declared inside the file (which makes sense since we can add multiple items in a single Swift file). On the other hand, since package.swift acts as a manifest, it makes sense to directly reflect the folder structure of our package.
When everything is correctly named, we run a build, and Xcode will autogenerate a static variable module added to the Bundle class. With this, we can now load the JSON file as follows:
let jsonFileURL = Bundle.module.url(forResource: file, withExtension: "json")
Conclusion
When developing a package, we must respect the names we declare in our package.swift in our folder structure. To call our JSON, we must use the autogenerated static variable module (another option could be to have this module variable as an extension in our snippets, but if it’s not being autogenerated, it’s likely because something is wrong in your package.swift).
- You can check the complete package on Github