我正在 Mac 上使用 Swift 开发一些服务器端代码,但最终部署在 Linux 上。我使用 Swift 包管理器创建了我的项目结构。我已经为类创建了几个 XCTestCase 单元测试。但是,我注意到,如果我将目标产品设置为 .executable
,当我运行 swift test
时,我会得到类似于以下内容的输出:
Compile Swift Module 'MyProjUtilTests' (3 sources) Linking ./.build/x86_64-apple-macosx10.10/debug/MyProjUtilPackageTests.xctest/Contents/MacOS/MyProjUtilPackageTests Undefined symbols for architecture x86_64:
"__T012MyProjUtil16PropertyListUtilCMa", referenced from: __T017MyProjUtilTests20PropertyListUtilTestC16testReadFromFileyyF in PropertyListUtilTest.swift.o "__T012MyProjUtil3FooCMa", referenced from: __T017MyProjUtilTests03FooC0C07testRunD0yyFSSyKXKfu_ in FooTests.swift.o "__T012MyProjUtilAAVABycfC", referenced from: __T017MyProjUtilTestsAAC11testExampleyyFSSyKXKfu_ in MyProjUtilTests.swift.o ld: symbol(s) not found for architecture x86_64 :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 /Volumes/Untitled/SwiftDev/MyProj/MyProjUtil/.build/debug.yaml test
但是,如果我将目标产品更改为 .library
,并运行 swift test
,它将执行我的测试并退出,不会出现错误。这是 Swift 包管理器中的错误吗?我是否需要做其他事情才能将单元测试包含在我的可执行产品中?或者这是预期的行为?谁能解释一下我在这里看到的内容以及为什么?谢谢!!
最佳答案
是的,这是预期的行为。
您可以在 Package.swift
中制定三个目标。 “MyAppLibTests”、“MyAppLib”和“MyAppExec”。
“MyAppLibTests”依赖于“MyAppLib”。 “MyAppExec”还依赖于“MyAppLib”。 “MyAppLib”取决于您可能拥有的任何外部依赖项。
您的目录结构可能如下所示:
+-- Package.swift
|
+-- Sources/
| |
| +-- MyAppLib/
| | ...files...
| |
| +-- MyAppLibExec/
| |
| +-- main.swift
|
+-- Tests/
|
+-- MyAppLibTests/
|
+-- MyTestCase.swift
然后在你的 main.swift
中,你会import MyAppLib; import Foundation
然后也许解析命令行参数和环境变量。将选项传递到库的主入口点。类似 MyAppMain().run(option: parsedValue, option2: parsedValue2)
奖励:要获取命令行参数,它们位于字符串数组中:Commandline.arguments
。要获取环境变量,它们位于字符串到字符串的字典中:ProcessInfo.processInfo.environment["SOME_ENV_VAR"]
关于swift - "swift test"失败并显示 "executable"但不是 "library"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49394059/