2016-04-02 30 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不客气!我相信你会和他们一起流动。 :) –

相关问题