kar*_*rma 5 android android-espresso
我正在使用 espresso 编写一些 UI 测试用例。我的应用程序包含一个 webview,我能够使用以下代码对 webview 内的按钮执行 webClick,该代码使用元素 Id 来查找元素:
onWebView()
.withElement(findElement(Locator.ID, "expandbtn"))
.perform(webClick());
Run Code Online (Sandbox Code Playgroud)
假设 webview 有带有文本“展开”的按钮。是否可以使用按钮上的文本而不是定位器 ID 来执行 webClick?
是的,有一种方法可以使用按钮上的文本来单击 Web 元素。您可以尝试使用 Xpath 表达式而不是 id 来查找元素:
onWebView().withElement(findElement(Locator.XPATH, xpath_expression)).perform(webClick());
Run Code Online (Sandbox Code Playgroud)
xpath_expression 是基于 html 源的元素的 Xpath。
"//button[contains(text(),'Expand')]"
Run Code Online (Sandbox Code Playgroud)
例如,如果按钮的文本位于子 span 元素内:
"//button[@type='%your button type%']/span[text()='Expand']/.."
Run Code Online (Sandbox Code Playgroud)
但请记住,Xpath 是查找项目的较慢方法之一。