服务器端Swift:测试使用捆绑包的代码

时间:2016-12-27 06:29:15

标签: 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 = bundlePath.appendingPathComponent("Test.plist")
plistDict = NSDictionary(contentsOfFile: plistPath)

当我在XCTests单元中运行时,plistPath是:

  

/Applications/Xcode-8.2.app/Contents/Developer/Platforms/MacOSX.platform/Developer/Library/Xcode/Agents/Test.plist

这不是很有用。

我注意到的一件事是“常规”选项卡下没有“主机应用程序:”的选项。

思想?

1 个答案:

答案 0 :(得分:0)

我还没能完全回答这个问题,但是为我的情况提出了解决办法。我使用Perfect File类(参见https://github.com/PerfectlySoft/Perfect.git),只是在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()
    }

有关完整背景,请参阅https://github.com/crspybits/SMServerLib