我目前正在尝试了解在Swift软件包中导入依赖项的机制,并且遇到了测试问题。希望有人可以解释我在做什么错。我将逐步描述问题,以便您可以轻松地重现它。
因此,我正在使用swift package init --type executable
创建一个新的Swift包。此命令创建基本的Swift包结构:
Artems-MacBook-Pro:SwiftExample artem$ swift package init --type executable
Creating executable package: SwiftExample
Creating Package.swift
Creating README.md
Creating .gitignore
Creating Sources/
Creating Sources/SwiftExample/main.swift
Creating Tests/
Creating Tests/LinuxMain.swift
Creating Tests/SwiftExampleTests/
Creating Tests/SwiftExampleTests/SwiftExampleTests.swift
Creating Tests/SwiftExampleTests/XCTestManifests.swift
该程序包本身称为SwiftExample
。如您所见,该命令还创建了一个单元测试用例(SwiftExampleTests.swift
)的示例。
然后,我创建一个名为Car.swift
的简单类,并将其放入Sources/SwiftExample/Classes/
目录中:
// Sources/SwiftExample/Classes/Car.swift
class Car {
init() {
print("I'm a car!")
}
}
在main.swift
文件中,我可以创建Car类的实例,并且一切正常:
// Sources/SwiftExample/main.swift
print("Hello, world!")
let car = Car()
输出为:
Hello, world!
I'm a car!
但是问题是我无法在测试文件中使用此类。例如,我试图在Car
文件的testExample()
函数中创建SwiftExampleTests.swift
类的实例:
import XCTest
import class Foundation.Bundle
@testable import SwiftExample
final class SwiftExampleTests: XCTestCase {
func testExample() throws {
let car = Car()
<other code goes here>
}
<other code goes here>
}
如您所见,我已经使用关键字@testable
导入了模块本身。但是,当我运行swift test
命令时,出现了这个奇怪的错误:
Compile Swift Module 'SwiftExample' (2 sources)
Compile Swift Module 'SwiftExampleTests' (2 sources)
Linking ./.build/x86_64-apple-macosx10.10/debug/SwiftExample
/Users/artem/Playgrounds/SwiftExample/Tests/SwiftExampleTests/SwiftExampleTests.swift:9:13: warning: initialization of immutable value 'car' was never used; consider replacing with assignment to '_' or removing it
let car = Car()
~~~~^~~
_
Linking ./.build/x86_64-apple-macosx10.10/debug/SwiftExamplePackageTests.xctest/Contents/MacOS/SwiftExamplePackageTests
Undefined symbols for architecture x86_64:
"_$S12SwiftExample3CarCACycfC", referenced from:
_$S17SwiftExampleTestsAAC04testB0yyKF in SwiftExampleTests.swift.o
"_$S12SwiftExample3CarCMa", referenced from:
_$S17SwiftExampleTestsAAC04testB0yyKF in SwiftExampleTests.swift.o
ld: symbol(s) not found for architecture x86_64
<unknown>:0: error: link command failed with exit code 1 (use -v to see invocation)
error: terminated(1): /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift-build-tool -f /Users/artem/Playgrounds/SwiftExample/.build/debug.yaml test output:
我在这里肯定做错了什么,但是我在官方文档中找不到任何有关此问题的信息。有人知道这里发生了什么以及如何解决吗?