Swift 5.3
注意:Swift 5.3 包含Package Manager Resources SE-0271 功能,可用于应用程序包和测试包资源。
资源并不总是供软件包的客户使用;资源的一种用途可能包括仅单元测试需要的测试夹具。此类资源不会与库代码一起合并到包的客户端中,而只会在运行包的测试时使用。
Swift 4、5:
let testBundle = Bundle(for: type(of: self))
guard var fileUrl = testBundle.url(forResource: "imageName", withExtension: "png")
else { fatalError() }
// path approach
guard let filePath = testBundle.path(forResource: "dataName", ofType: "csv")
else { fatalError() }
let fileUrl = URL(fileURLWithPath: filePath)
Bundle 提供了发现配置的主要路径和测试路径的方法:
@testable
import Example
class ExampleTests: XCTestCase {
func testExample() {
let bundleMain = Bundle.main
let bundleDoingTest = Bundle(for: type(of: self ))
let bundleBeingTested = Bundle(identifier: "com.example.Example")!
print("bundleMain.bundlePath : \(bundleMain.bundlePath)")
// …/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/Library/Xcode/Agents
print("bundleDoingTest.bundlePath : \(bundleDoingTest.bundlePath)")
// …/PATH/TO/Debug/ExampleTests.xctest
print("bundleBeingTested.bundlePath : \(bundleBeingTested.bundlePath)")
// …/PATH/TO/Debug/Example.app
print("bundleMain = " + bundleMain.description) // Xcode Test Agent
print("bundleDoingTest = " + bundleDoingTest.description) // Test Case Bundle
print("bundleUnderTest = " + bundleBeingTested.description) // App Bundle
Xcode URL 将位于 Developer/Xcode/DerivedData 中,类似于 ...
file:///Users/
UserName/
Library/
Developer/
Xcode/
DerivedData/
App-qwertyuiop.../
Build/
Products/
Debug-iphonesimulator/
AppTests.xctest/
imageName.png
...与Developer/CoreSimulator/Devices URL 不同
file:///Users/
UserName/
Library/
Developer/
CoreSimulator/
Devices/
_UUID_/
data/
Containers/
Bundle/
Application/
_UUID_/
App.app/
还请注意,单元测试可执行文件默认情况下与应用程序代码链接。但是,单元测试代码应该只在测试包中具有 Target Membership。应用程序代码应仅在应用程序包中具有目标成员资格。在运行时,单元测试目标包是injected into the application bundle for execution。
Swift 包管理器 (SPM) 4:
let testBundle = Bundle(for: type(of: self))
print("testBundle.bundlePath = \(testBundle.bundlePath) ")
注意:默认情况下,命令行swift test 将创建一个MyProjectPackageTests.xctest 测试包。而且,swift package generate-xcodeproj 将创建一个 MyProjectTests.xctest 测试包。这些不同的测试包具有不同的路径。 另外,不同的测试包可能有一些内部目录结构和内容差异。
在任何一种情况下,.bundlePath 和 .bundleURL 都会返回当前在 macOS 上运行的测试包的路径。但是,Bundle 目前尚未在 Ubuntu for Swift 4 中实现。
此外,Swift 4 命令行 swift build 和 swift test 不提供复制资源的机制。
但是,通过一些努力,可以在 macOS Xcode、macOS 命令行和 Ubuntu 命令行环境中设置使用 Swift Package Manger 的进程。一个例子可以在这里找到:004.4'2 SW Dev Swift Package Manager (SPM) With Resources Qref