2016-11-23 66 views
1

我製作了一個簡單的應用程序,它將數據添加到數據庫中,然後進行檢索。在創建單元測試時,看起來URLSession.Shared.dataTask未運行。我可以通過我設置的打印語句的輸出來看到這一點。下面是我的代碼:Xcode:單元測試時URL共享會話未運行

func addChild(childName:String,dob:String,number1:String,number2:String,parentNum:String,parentPass:String,notes:String){ 

    //url to php file 
    let url = NSURL(string:"http://localhost/addChild.php") 

    //request to this file 
    let request = NSMutableURLRequest(url: url as! URL) 

    //method to pass data to this file 
    request.httpMethod = "POST" 

    //body to be appended to url 
    let body = "childName=\(childName)&dateOfBirth=\(dob)&contact1=\(number1)&contact2=\(number2)&parentAccNum=\(parentNum)&parentAccPass=\(parentPass)&notes=\(notes)" 
    request.httpBody = body.data(using: String.Encoding.utf8) 
    print("a") 
    //launching the request 
    URLSession.shared.dataTask(with: request as URLRequest, completionHandler: { (data:Data?, response:URLResponse?, error:Error?) in 
     print("b") 
     if (error == nil){ 
      print("c") 
      //send request 
      //get main queue in code process to communicate back to user interface 
      DispatchQueue.main.async(execute: { 

       do{ 
        //get json result 
        let json = try JSONSerialization.jsonObject(with: data!,options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary 
        print("d") 
        //assigning json to parseJSON in guard/secure way 
        //checking whether the parsing has worked 
        guard let parseJSON = json else{ 
         print("Error while parsing") 
         return 
        } 

        //get id from parseJSON dictionary 
        let id = parseJSON["id"] 

        //if there is some id value 
        if id != nil{ 
         print(parseJSON) 
         self.success = true 
         print("success") 
        } 
       } 
       catch{ 
        print("Caught an error:\(error)") 
       } 


      }) 
     } 
      //if unable to proceed request 
     else{ 
      print("Error:\(error)") 
     } 
     //launch prepared session 
    }).resume() 
} 

然後下面是我的單元測試腳本:這裏

import XCTest 
@testable import computerScienceCoursework 


class addChildTest: XCTestCase { 
    //Setting up the values of the text fields 
    var testChildName:String = "Test name" 
    var testDOB:String = "99/99/99" 
    var testContact1:String = "00000000000" 
    var testContact2:String = "11111111111" 
    var testParAccNum:String = "-1" 
    var testParAccPass:String = "Password" 
    var testNotes:String = "Insert notes here" 



    var newChild = AddChildController() 

    override func setUp() { 
     super.setUp() 
     // Put setup code here. This method is called before the invocation of each test method in the class. 


     } 

    override func tearDown() { 
    // Put teardown code here. This method is called after the invocation of each test method in the class. 
     super.tearDown() 
    } 

    func testAddChildIsWorking(){ 
     //Assigning the values to the text fields 
     newChild.addChild(childName: testChildName,dob: testDOB,number1: testContact1,number2: testContact2,parentNum: testParAccNum,parentPass: testParAccPass,notes: testNotes) 
     XCTAssert(newChild.success == true) 
    } 

} 

回答

0

問題是,你知道鴕鳥政策當異步任務完成併成功屬性得到更新。 針對您的問題有一些可能的解決方案,其中之一是爲您的方法添加完成處理程序。

func addChild(childName:String,dob:String,number1:String,number2:String,parentNum:String,parentPass:String,notes:String, completion: (Bool) -> Void){ 
    //url to php file 
    let url = NSURL(string:"http://localhost/addChild.php") 

    //request to this file 
    let request = NSMutableURLRequest(url: url as! URL) 

    //method to pass data to this file 
    request.httpMethod = "POST" 

    //body to be appended to url 
    let body = "childName=\(childName)&dateOfBirth=\(dob)&contact1=\(number1)&contact2=\(number2)&parentAccNum=\(parentNum)&parentAccPass=\(parentPass)&notes=\(notes)" 
    request.httpBody = body.data(using: String.Encoding.utf8) 
    print("a") 
    //launching the request 
    URLSession.shared.dataTask(with: request as URLRequest, completionHandler: { (data:Data?, response:URLResponse?, error:Error?) in 
     print("b") 
     if (error == nil){ 
      print("c") 
      //send request 
      //get main queue in code process to communicate back to user interface 
      DispatchQueue.main.async(execute: { 

       do{ 
        //get json result 
        let json = try JSONSerialization.jsonObject(with: data!,options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary 
        print("d") 
        //assigning json to parseJSON in guard/secure way 
        //checking whether the parsing has worked 
        guard let parseJSON = json else{ 
         print("Error while parsing") 
         completion(false) 
         return 
        } 

        //get id from parseJSON dictionary 
        let id = parseJSON["id"] 

        //if there is some id value 
        if id != nil{ 
         print(parseJSON) 
         self.success = true 
         print("success") 
         completion(true) 
        } 
       } 
       catch{ 
        print("Caught an error:\(error)") 
        completion(false) 
       } 

      }) 
     } 
      //if unable to proceed request 
     else{ 
      print("Error:\(error)") 
      completion(false) 

     } 
     //launch prepared session 
    }).resume() 
} 

然後在您的測試方法中,您可以使用該方法。

 func testAddChildIsWorking() 
     { 
      let asyncExpectation = expectationWithDescription("addChildIsWorkingFunction") 

      newChild.addChild(childName: testChildName, dob: testDOB, number1: testContact1, 
      number2: testContact2, parentNum: testParAccNum, parentPass: testParAccPass, notes: testNotes) { (success) in 

       asyncExpectation.fulfill() 

      } 

      self.waitForExpectationsWithTimeout(10) { error in 

       XCTAssert(newChild.success == true) 
      }  
     } 

waitForExpectationWithTimeout正在等待,直到觸發完成或發生超時。這樣你可以測試你的異步代碼。 欲瞭解更多信息,請查看link

希望有所幫助。

+0

非常感謝你,我真的不認爲我會得到答覆:) –

+0

不客氣。如果答案解決了您的問題,請接受它們。 –

+0

其實很小的問題,newChild.addChild調用正在創建一個錯誤:「在調用中額外的參數'註釋'」。你知道這是什麼情況嗎? –