Swift - 如何测试点击按钮时标签是否已更新

Swift - How do you test whether a label has been updated when a button is tapped

我使用了一个非常简单的计算器,我正在尝试测试点击按钮时标签是否会更新。

我的测试方法是这样的:

let app = XCUIApplication()
app.buttons["9"].tap()

我可以直观地看到正在更新的标签,但我不确定如何测试它。

我想我需要使用XCUIElementQuery API 来查询标签,然后断言标签文本已更改。我只是不确定该怎么做。

我不确定以下问题:

  • Do I need to know what the value is for the label to be able to query?
  • Is there a way of querying for the label without knowing what the value is when the application starts?

使用 UI 测试,您可能需要以不同的方式思考您的问题。不要断言某些东西 已更改 ,而是检查新事物 是否存在

实际上,这意味着检查是否出现了具有您期望值的标签。不要检查现有状态是否已更改为正确状态。

因此,在您的示例中,您可以执行以下操作。这将检查当您点击“9”按钮时是否出现带有文本“42”的标签。

let app = XCUIApplication()
app.buttons["9"].tap()
XCTAssert(app.staticTexts["42"].exists)

我会说你为你想要点击的按钮设置不同的accessibilityLabelaccessibilityIdentifier,然后比较tap()前后的值并检查是否[=13] =] 已使用 XCTAssertNotEqual 断言更改,

在应用代码中:

button.accessibilityIdentifier = "TappableButton"

然后在测试文件中:

let app = XCUIApplication() let buttonLabel = app.buttons["TappableButton"].label app.buttons["TappableButton"].tap() XCTAssertNotEqual(buttonLabel, app.buttons[TappableButton].label)