2016-12-27 26 views
0

我使用服务器端的斯威夫特,做后做我的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

这不是很有用。

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

想法?

回答

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为完整的上下文。