UITests терпит неудачу при запуске в группе, но успешно, когда выполняется независимо - PullRequest
0 голосов
/ 28 мая 2018

В настоящее время я работаю над проектом со множеством асинхронного кода и пишу UITests для этого проекта.Во время разработки я запускаю их один за другим, но никогда в группе.Поэтому я подумал, что испытания проходят успешно.Но при тестировании их всех вместе большинство из них терпят неудачу.Я правильно выполнил настройку и демонтаж.Я исследовал причины такого поведения, но не смог найти хорошего ответа на эту проблему.Это как ожидание ожидания не работает должным образом ...

Вот метод, который делает большинство проблем.Я вызываю его каждый раз, когда хочу дождаться появления элемента.

/*
* This method will wait for an element (10 seconds default) afterwards it will assert it existence
*
* - parameter toAppear:The condition we are waiting for.
* - parameter element: The element to be expected
* - parameter timeout: The MAX time that the function will wait for the element, 10 seconds if none is given
* - parameter file:    The file where the error will be displayed, the current file will be used in case none is provided
* - parameter line:    The code line where the error will be displayed, the current line will be used in case none is provided
*/
static func assertForElement(toAppear: Bool, _ element: XCUIElement?, timeout: TimeInterval = 10, file: String = #file, line: Int = #line) {

    guard let currentTestCase = BaseXCTestCase.CurrentTestCase else {
        return
    }

    guard let element = element else {
        let message = "Element cannot be empty"

        currentTestCase.recordFailure(withDescription: message, inFile: file, atLine: line, expected: true)

        return
    }

    let existsPredicate = NSPredicate(format: "exists == \(toAppear)")

    currentTestCase.expectation(for: existsPredicate, evaluatedWith: element, handler: nil)
    currentTestCase.waitForExpectations(timeout: timeout) { [weak currentTestCase] (error: Error?) in

        if (error != nil) {
            let appearMessage = "Failed to find \(String(describing: element)) after \(timeout) seconds."
            let disappearMessage = "Failed to see \(String(describing: element)) disappear after \(timeout) seconds."

            currentTestCase?.recordFailure(withDescription: ((toAppear == false) ? disappearMessage : appearMessage), inFile: file, atLine: line, expected: true)
        }
    }
}

Есть ли у кого-нибудь хороший метод для UITest асинхронного кода?

Большое спасибо взаранее!

ОБНОВЛЕНИЕ

Вот предупреждения об ошибках, которые я получаю.

большую часть времени я просто получаю: Asynchronous wait failed: Exceeded timeout of 10 seconds, with unfulfilled expectations: "Expect predicate существует == 1for object но элемент виден и кликабелен в симуляторе.С другой стороны, я получаю: caught "NSInternalInconsistencyException", "API violation - creating expectations while already in waiting mode." ...

1 Ответ

0 голосов
/ 28 мая 2018

Ваше сообщение об ошибке означает, что вы создаете дополнительные ожидания после того, как позвонили waitForExpectations.

Сначала создайте все свои ожидания, а затем вызовите waitForExpectations в качестве последней строки кода в своем тесте.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...