当特定文本部分可变时查找元素的特定文本(selenium Java)

问题描述 投票:0回答:1

对于以下元素,我需要找到重新排队、应用程序退出和问候语启动的计数。 此外,我需要验证每个事件的计数。

<div _ngcontent-ome-c213="" class="counts"> 0 Requeues<br _ngcontent-ome-c213=""> 0 App Exits<br _ngcontent-ome-c213=""> 2 Greets Started </div>

尝试过:

public void verifySessionMetricsWasGenerated(String metrics, int count) {
        assertThat(findElements(By.xpath("//div[contains(@class, 'counts') and contains(text(), '" + metrics + "')]")))
                .as("Did not find expected number of metrics '" + metrics + "' " + SpecContext.examSession())
                .hasSize(count);

得到:

Expected size: 1 but was: 0 in:
[]
Stack Trace:
java.lang.AssertionError: [Did not find expected number of metrics 'Greets Started' 
java selenium-webdriver xpath gettext verification
1个回答
0
投票

我认为解决这个问题的更简单方法是调用一个返回所有 3 个指标的方法,然后在测试中断言每个指标。

要返回所有指标,我们需要一个可以保存 3 个值的类。

指标.java

public class Metrics
{
    public String Requeues;
    public String AppExits;
    public String GreetsStarted;

    public Metrics(String requeues, String appExits, String greetsStarted) {
        Requeues = requeues;
        AppExits = appExits;
        GreetsStarted = greetsStarted;
    }
}

然后我们需要一个方法来返回包含 3 个值的

Metrics
实例,

public static Metrics getMetrics() {
    String counts = driver.findElement(By.cssSelector("div.counts")).getText();
    String[] countStrings = counts.split("\\n");

    return new Metrics(countStrings[0].split(" ")[0], countStrings[1].split(" ")[0], countStrings[2].split(" ")[0]);
}

然后我们进行测试本身,

String expectedRequeues = "0";
String expectedAppExits = "0";
String expectedGreetsStarted = "2";

driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get(url);

Metrics metrics = getMetrics();
Assert.assertEquals(metrics.Requeues, expectedRequeues, "Verify requeues");
Assert.assertEquals(metrics.AppExits, expectedAppExits, "Verify app exits");
Assert.assertEquals(metrics.GreetsStarted, expectedGreetsStarted, "Verify greets started");
© www.soinside.com 2019 - 2024. All rights reserved.