Swift unit tests, including and using .json files

Note: I’m running everything on Ubuntu 20.0.4 using Swift version 5.7.1. I’m assuming everything listed below works on Mac etc. as well.

I have a simple Eureka client package (named SwiftEureka) that I’ve been working on. Now I’ve tested it against a running instance of Eureka but I want to write some unit tests where I don’t need the server running. The idea simply being that I have a bunch of .json files which contain the JSON responses, taken from Eureka, for various REST calls.

So, to summarise, I basically want to have .json files within my Tests folder and use them within my unit tests.

Let’s assume we have our Tests/EurekaTests folder and within that we have a file named applications.json. We need to add this to the Package.swift file under the .testTarget section, like this

.testTarget(
   name: "EurekaTests",
   dependencies: ["SwiftEureka"],
      resources: [
         .process("applications.json")
      ]),

Now the file will be seen by Swift as part of the package’s bundle.

Next, we need to load the file into our tests. We do this by using the Bundle object, like this

guard let path = Bundle.module.url(forResource: "applications", withExtension: "json") else {
   XCTFail("Missing file: applications.json")
   return
}

let json = try Data(contentsOf: path)
let wrapper = try JSONDecoder().decode(ApplicationsWrapper.self, from: json)