2016-12-27 30 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爲完整的上下文。