You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将XCUI测试转化为使用一致选择器的自动化测试

Refactored XCUI Test with Consistent Selectors

Got it, let's fix up that XCUI test to use clean, consistent selectors instead of that overly clunky identifier string. The original code was trying to target elements with a jumbled mix of labels and news text, which is fragile and hard to maintain. Here's how to refactor it properly while keeping all technical details intact:

Key Improvements

  • Replaced the messy combined identifier with semantic accessibility identifiers for each interactive element (like buttons)
  • Separated dynamic content (news headlines) from element selectors, using static text queries to verify their presence instead of treating them as identifiers

Refactored Code

func testExample() {
    let app = XCUIApplication()
    
    // Use consistent, stable accessibility identifiers for interactive elements
    let menuButton = app.buttons["menuButton"]
    let addEBooksButton = app.buttons["addEBooksButton"]
    
    // Example test interactions (adjust based on your actual test flow)
    menuButton.tap()
    addEBooksButton.tap()
    
    // Verify dynamic news content using static text queries
    let cambridgeAnalyticaHeadline = app.staticTexts["UK Information Commissioner's Office raids Cambridge Analytica's London office"]
    XCTAssertTrue(cambridgeAnalyticaHeadline.exists, "Cambridge Analytica raid headline should be visible")
    
    let nasaLandslideHeadline = app.staticTexts["NASA's got a computer model for predicting landslides"]
    XCTAssertTrue(nasaLandslideHeadline.exists, "NASA landslide prediction headline should be visible")
    
    // Add more assertions for other news items as needed
}

Why This Works Better

  • Maintainability: If the menu or button labels change, you only need to update the accessibility identifier in one place (both the app code and test) instead of hunting through a long string.
  • Stability: Dynamic content like news headlines shouldn't be used as identifiers—they can change frequently, breaking your tests. Using static text queries lets you verify the content without tying your test to unstable values.
  • Readability: Anyone looking at the test can immediately understand what each element is and what the test is doing, instead of parsing a messy combined identifier.

内容的提问来源于stack exchange,提问作者liminal18

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 03:35:45