EarlGrey测试segue到ViewController

时间:2017-09-15 10:40:26

标签: swift xctest earlgrey

我试图在成功登录时测试一个新的viewcontroller出现,但我没有太多运气,也无法理解为什么。

测试:

func testLoginButtonPerformsSegueWithValidEmailAndPassword() {
    let titleLabel = EarlGrey.select(elementWithMatcher: grey_kindOfClass(MyBillsViewController.self))
    let assertion = grey_sufficientlyVisible()
    let conditionName = "Wait for title to appear in next MyBillsViewController"

    login(email: registeredEmail,
          password: password)

    let appearedSuccesfully = waitForSuccess(of: assertion,
                                             with: titleLabel,
                                             conditionName: conditionName)

    GREYAssertTrue(appearedSuccesfully, reason: "Title Label appeared with correct text")
}

登录助手方法:

func login(email: String, password: String) {
    let emailTextField = grey_accessibilityID(TestAccesID.emailTextField)
    let passwordTextField = grey_accessibilityID(TestAccesID.passwordTextField)
    let loginButton = grey_accessibilityID(TestAccesID.loginButton)

    EarlGrey.select(elementWithMatcher: emailTextField)
        .perform(grey_tap()).perform(grey_typeText(email))
    EarlGrey.select(elementWithMatcher: passwordTextField)
        .perform(grey_tap()).perform(grey_typeText(password))
    EarlGrey.select(elementWithMatcher: loginButton).perform(grey_tap())
}

GreyCondition Helper方法:

func waitForSuccess(of assertion: GREYMatcher,
                    with element: GREYElementInteraction,
                    conditionName: String ) -> Bool {
    var success = false

    GREYCondition(name: conditionName, block: { () -> Bool in

        let errorOrNil = UnsafeMutablePointer<NSError?>.allocate(capacity: 1)
        errorOrNil.initialize(to: nil)

        element.assert(with: assertion, error: errorOrNil)

        success = errorOrNil.pointee == nil
        errorOrNil.deinitialize()
        errorOrNil.deallocate(capacity: 1)

        return success
    }).wait(withTimeout: 3.0)

    return success
}

尽管登录成功并且对正确的视图控制器有明确的判断,但我仍然遇到失败的测试,但我不确定是什么。任何帮助都会很棒,谢谢。

1 个答案:

答案 0 :(得分:0)

异步功能测试是一项众所周知的挑战。如果设置断点,我认为问题在于:

GREYCondition(name: conditionName, block: {
  //Do stuff here.
}).wait(withTimeout: 3.0)

此块未立即输入,然后执行后直接转到return success行之后的wait(其中success = false)。

要解决此问题,请尝试实施XCWaitCompletionHandlerXCTestExpectation

func expectation(description: String) -> XCTestExpectation

func waitForExpectations(timeout: TimeInterval, handler: XCWaitCompletionHandler? = nil)