Swift3 服务器端Swift:使用Bundle的测试代码
我正在使用服务器端Swift,并在执行以下操作后在Xcode中进行开发:Swift3 服务器端Swift:使用Bundle的测试代码,swift3,bundle,xcode8,server-side-swift,Swift3,Bundle,Xcode8,Server Side Swift,我正在使用服务器端Swift,并在执行以下操作后在Xcode中进行开发: swift package generate-xcodeproj 我有一个类,它使用Bundle(以前是NSBundle)将服务器中的某些设置加载到.plist文件中。它在服务器本身中运行时工作正常,但是当我为这个类创建一些单元测试时,我无法访问.plist文件所在的目录。相关的代码片段是: let bundlePath = Bundle.main.bundlePath as NSString let plistPath
swift package generate-xcodeproj
我有一个类,它使用Bundle
(以前是NSBundle
)将服务器中的某些设置加载到.plist文件中。它在服务器本身中运行时工作正常,但是当我为这个类创建一些单元测试时,我无法访问.plist文件所在的目录。相关的代码片段是:
let bundlePath = Bundle.main.bundlePath as NSString
let plistPath = bundlePath.appendingPathComponent("Test.plist")
plistDict = NSDictionary(contentsOfFile: plistPath)
当我在单元测试中运行这个时,plistPath是:
/Applications/Xcode-8.2.app/Contents/Developer/Platforms/MacOSX.platform/Developer/Library/Xcode/Agents/Test.plist
这不是很有用
我注意到,在General选项卡下没有“Host Application:”选项
想法?我还不能完全回答这个问题,但我想出了一个解决我的情况的办法。我使用的是Perfect File类(请参阅),只是在setUp()方法中动态创建XCTest用例所需的文件。幸运的是,我对文件内容有相当简单的需求。以下是我的XCTest文件的初始部分:
import XCTest
import SMServerLib
import PerfectLib
class TestPlistDictLoader: XCTestCase {
var plistFileName:String! = "TestPlistDictLoader.plist"
var pathName:String! = "/tmp"
override func setUp() {
super.setUp()
// A bit of a hack, but I can't figure out a way otherwise to access the install directory where the code is running.
// See also http://stackoverflow.com/questions/41340114/server-side-swift-testing-code-that-uses-bundle
// The only downside is that these tests don't test the `init(plistFileNameInBundle filename:String)` constructor that uses the Bundle.
// Write the .plist file to a known location. Use only pure Swift methods.
let plistPath = (pathName as NSString).appendingPathComponent(plistFileName)
let plist = File(plistPath)
try! plist.open(.write)
try! plist.write(string: "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n" +
"<plist version=\"1.0\">\n" +
"<dict>\n" +
"<key>MyString</key>\n" +
"<string>Hello World!</string>\n" +
"<key>MyInteger</key>\n" +
"<integer>100</integer>\n" +
"</dict>\n" +
"</plist>\n"
)
plist.close()
}
导入XCTest
导入SMServerLib
导入PerfectLib
类TestPlistDictLoader:XCTestCase{
var plistFileName:String!=“TestPlistDictLoader.plist”
变量路径名:字符串!=“/tmp”
覆盖函数设置(){
super.setUp()
//有点像黑客,但我想不出其他方法来访问运行代码的安装目录。
//另见http://stackoverflow.com/questions/41340114/server-side-swift-testing-code-that-uses-bundle
//唯一的缺点是这些测试不测试使用捆绑包的`init(plistFileNameInBundle filename:String)`构造函数。
//将.plist文件写入已知位置。仅使用纯Swift方法。
让plistPath=(路径名为NSString)。追加路径组件(plistFileName)
设plist=File(plistPath)
试试!plist.open(.write)
try!plist.write(字符串:“\n”+
“\n”+
“\n”+
“\n”+
“我的字符串\n”+
“你好,世界!\n”+
“MyInteger\n”+
“100\n”+
“\n”+
“\n”
)
plist.close()
}
有关完整上下文,请参见