2016-11-23 91 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调用正在创建一个错误:“在调用中额外的参数'注释'”。你知道这是什么情况吗? –