XCTest框架下如何获取XCUIElement的父元素?
parent() Doesn't Exist Hey there! I totally get your scenario—you're dealing with dynamic static text labels, so you want to use a stable button identifier to navigate up to its parent cell, then access that other element. Since XCUIElement doesn't have a built-in parent() method, let's walk through the best ways to solve this.
The Most Reliable Approach: Reverse Query with containing
Instead of trying to "climb up" from the button to its parent, we can reverse the query to directly find the cell that contains your target button. This is way more stable than relying on traversing hierarchy, and it plays to XCUI's strengths.
Here's how to adjust your code:
// First, find the cell that contains the button with identifier "primaryButton" let targetCell = XCUIApplication().tables.cells .containing(.button, identifier: "primaryButton") .firstMatch // Now access the other element inside this cell if let otherElementLabel = targetCell.otherElements.firstMatch.label { print("Found the value: \(otherElementLabel)") }
Why this works:
- The
containingmethod lets you filter parent elements by their child attributes. So we're asking for all cells that have a button with the identifier "primaryButton", then grabbing the first match (which should be your target cell). - This avoids fragile hierarchy assumptions—even if the UI shifts a bit, as long as the button stays inside the cell, this will work.
If You Really Need to Traverse Up (Not Recommended)
If for some reason you need to explicitly traverse up the element hierarchy (e.g., more complex UI structures), you can parse the element's debugDescription to find parent references. However, this is not ideal because memory addresses (like 0x00006b) are random and can change between runs.
But just for completeness, here's a rough idea:
let btnPrimary = XCUIApplication().tables.buttons["primaryButton"] let debugText = btnPrimary.debugDescription // Parse the debug text to find the parent cell's address (this is fragile!) // Look for lines like "Parent: Cell, 0x123456..." // Then you could construct a query using that address, but this is brittle
Again, I strongly advise against this approach—it's prone to breaking when the app's UI changes, or even between test runs.
Final Notes
Stick with the containing method whenever possible. It's the intended way to handle these scenarios in XCTest, and it keeps your tests robust against dynamic content or minor UI tweaks.
内容的提问来源于stack exchange,提问作者sasorihuriko

