2016-04-02 83 views
-1

這是我的查詢。它位於測試目標中。我在AppDelegate.swift中設置了applicationID和clientKey。你如何用Xcode編寫單元測試(在我的案例中是Swift)?

我在AppDelegate.swift中放置了一個斷點,所以在運行測試時肯定會發生。它也達到了我在下面代碼的第5行之前設置的斷點(customer.saveinbackgroundWithBlock ...)。但是當我在該行後面放置斷點時,它不會觸及它,並且測試會「成功」。另外,Parse Dashboard顯示沒有客戶被添加。

我在正常的應用程序目標測試了相同的查詢,並且工作。只是不在測試目標。

func testCustomersExistCase() { 
    // Save a test customer 
    let customer = Customer(firstName: "Jonathan", lastName: "Goldsmith", email: "[email protected]", streetAddress: "100 Main St", city: "Monterrey", state: "Texas", zipCode: "55555") 
    customer.shopID = "dosequis" 

    customer.saveInBackgroundWithBlock({ 
     (success: Bool, error: NSError?) -> Void in 
      if success { 
       print("This test should work.") 
       self.customerSearchViewControllerDataSource.getAllCustomers(self.customeSearchViewController) 

       // Check if it's in the customers array 
       for customerResult in self.customeSearchViewController.data! { 
        if customerResult.objectId == customer.objectId { 
         XCTAssertTrue(true, "Success! Customer was added.") 

         // Delete customer if test had succeeded. 
         customer.deleteInBackgroundWithBlock({ 
          (success: Bool, error: NSError?) -> Void in 
          if success { 
           print("Clean-up after test was successful") 
          } else { 
           print("Need to delete customer manually") 
          } 
         }) 
        } else { 
         XCTAssertTrue(false, "Query is broken. Customer was not retrieved") 
        } 
       } 
      } else { 
       print("This test will not work. Customer was not added to Parse") 
      } 
     if error != nil { 
      print("This test isn't working. Parse threw an error.") 
     } 
    }) 
} 

} 

回答

0

這是因爲發生在解析塊在不同的線程比你的測試執行上運行等測試完成不知情的解析塊做什麼。

要測試異步操作,您應該在您的XCTest子類中創建一個期望並調用waitForExpectation方法。這裏有一個簡單的例子:

視圖控制器W /法

class ViewController: UIViewController { 

override func viewDidLoad() { 
    super.viewDidLoad() 
    // Do any additional setup after loading the view, typically from a nib. 
} 

override func didReceiveMemoryWarning() { 
    super.didReceiveMemoryWarning() 
    // Dispose of any resources that can be recreated. 
} 

func getUserStuff(completionHandler: (succeeded: Bool) ->()) { 

} 
} 

測試:

func testGetUserInfo() { 

    let vc = ViewController() 

    let userOpExpectation: XCTestExpectation = expectationWithDescription("Got user info") 

    vc.getUserStuff { (succeeded) in 
     XCTAssert(succeeded, "Should get user stuff") 
     userOpExpectation.fulfill() 
    } 

    waitForExpectationsWithTimeout(5.0, handler: nil) 
} 

有很多是進入測試和蘋果提供了很多,無論是在包括道路代碼和文檔,查看:https://developer.apple.com/library/tvos/documentation/DeveloperTools/Conceptual/testing_with_xcode/chapters/04-writing_tests.html瞭解更多信息。

+0

謝謝!我在我的研究中確實看到了期望,但從未點擊過,我需要它們。 –

+0

@ArthurAyetiss不客氣!我相信你會和他們一起流動。 :) –

相關問題