Use resources in unit tests with Swift Package Manager

前端 未结 7 482
孤街浪徒
孤街浪徒 2020-12-08 21:12

I\'m trying to use a resource file in unit tests and access it with Bundle.path, but it returns nil.

This call in MyProjectTests.swift returns nil:

7条回答
  •  时光取名叫无心
    2020-12-08 21:28

    Currently, swift package manager (SPM) doesn't handle resources, here is an issue open in SPM's bug tracking system https://bugs.swift.org/browse/SR-2866.

    Until support for resources is implemented in SPM, I would copy resources to the locations where the result executable expects resources to be during runtime. You can know these locations by printing Bundle.resourcePath property. I would perform this copying automatically, using a Makefile for example. This way Makefile becomes a "build orchestrator" on top of SPM.

    I wrote an example to demonstrate how this approach works on MacOS and Linux -https://github.com/vadimeisenbergibm/SwiftResourceHandlingExample.

    The user would run make commands: make build and make test instead of swift build and swift test. Make will copy the resources to the expected locations (different on MacOS and Linux, during run and during tests).

提交回复
热议问题