Search code examples
iosjsonbundlexctest

How to manage static json files used in XCTests


I've got a bunch of static json files in a project that I'm using in unit tests in place of API responses. To get this to work, their target membership needs to be the production target else the files aren't found when I call Bundle.main.url(forResource: fileName, withExtension: "json") within the test. I can see that they are in the 'copy bundle resources' list in the 'build phases' of the production target.

But these file aren't needed in the project except in the test suites and I don't want them to take up space in the release build.

What is the best way to manage these files in my project if they are only needed for the test target?


Solution

  • Test resources belong in the test bundle. Access the test bundle by specifying a test file, not Bundle.main which is still the production bundle.

    For example, from within an XCTestCase subclass, you can do this:

    Bundle(for: type(of: self))
    

    Then you can query that bundle to fetch your stored JSON examples.