夫特2:
let testBundle = NSBundle(forClass: self.dynamicType)
let fileURL = testBundle.URLForResource("imageName", withExtension: "png")
XCTAssertNotNil(fileURL)
夫特3,4:
let testBundle = Bundle(for: type(of: self))
let fileURL = testBundle.url(forResource: "imageName", withExtension: "png")
XCTAssertNotNil(filePath)
捆綁提供了一些方法來發現爲您的配置的主要和測試路徑:
@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的6 | 7 | 8網址將在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/
還要注意單元測試可執行文件默認情況下,與應用程序代碼鏈接。但是,單元測試代碼只應在測試包中具有目標成員資格。應用程序代碼應該只在應用程序包中具有目標成員資格。在運行時,單元測試目標包是injected into the application bundle for execution。
夫特包管理器(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實施。
此外,命令行swift build
和swift test
目前不提供複製資源的機制。
但是,通過一些努力,可以爲macOS Xcode,macOS命令行和Ubuntu命令行環境中的資源設置使用Swift軟件包管理器的進程。一個例子可以在這裏找到:004.4'2 SW Dev Swift Package Manager (SPM) With Resources Qref
這個回答解決了問題,而無需更改代碼http://stackoverflow.com/a/24330617/468868 –