如何在Swift包中测试类



我目前正试图了解在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!

但问题是我不能在我的测试文件中使用这个类。例如,我试图在SwiftExampleTests.swift文件的testExample()函数中创建Car类的实例:

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:

我在这里肯定做错了什么,但我在官方文件中找不到任何关于此事的信息。有人知道这里发生了什么以及如何解决吗?

显然,这个问题在最新的Swift版本中不会再出现了。Car类可以导入,swift test命令不会失败。

记录在案,我当前的swift --version输出为:

swift-driver version: 1.45.2 Apple Swift version 5.6.1 (swiftlang-5.6.0.323.66 clang-1316.0.20.12)
Target: arm64-apple-macosx12.0

最新更新