【问题标题】:How to use Assert in Junit instead of if else?如何在 Junit 中使用 Assert 而不是 if else?
【发布时间】:2021-11-08 04:22:00
【问题描述】:

我有一种搜索方法,第一页上有一个维基百科的链接:

public void findWiki() {

    TryLink = chromeDriver.findElement(By.xpath("//a[@href='https://ru.wikipedia.org/wiki/%D0%A8%D0%BF%D0%B0%D0%B6%D0%BD%D0%B8%D0%BA']"));

    if (TryLink.isDisplayed()) {
        System.out.println("Yes link is there");
    } else {
        System.out.println("No link is there");
    }
}

该方法的实现:

@Test
public void googleSearchPF() {
    chromeDriver.get("https://www.google.com/webhp?hl=en&sa=X&ved=0ahUKEwi88p6D9vbyAhXhkIsKHffmA_oQPAgI");
    GoogleSearchPF googleSearchPF = PageFactory.initElements(chromeDriver, GoogleSearchPF.class);
    googleSearchPF.find("Gladiolus");
    googleSearchPF.findWiki();
}

测试有效,一切正常 - 它找到了链接。但是如何使用 assertTrue 实现链接检查?如果有,具体是怎样的?

看来应该是这样实现的:

Assertions.assertTrue(googleSearchPF.getAllElements().stream().anyMatch(x->x.isDisplayed()),
        "Wikipedia was not found");

【问题讨论】:

  • 这真的是测试没有业务代码吗?你为什么不直接做assertTrue(TryLink.isDisplayed())
  • 为什么googleSearchPF@Test注解?据我所知,该方法本身并不是测试。
  • 这不是商业代码。 googleSearchPF - 一个真正有效的测试。我只是想弄清楚如何正确编写 Assert 方法,以便在不使用 if else 的情况下正确检查链接。

标签: java selenium junit


【解决方案1】:

如果你看到assertTrue

assertTrue
public static void assertTrue(java.lang.String message,
                              boolean condition)
Asserts that a condition is true. If it isn't it throws an AssertionError with the given message.
Parameters:
message - the identifying message for the AssertionError (null okay)
condition - condition to be checked

现在,您的 findWiki() 方法确实包含 if 和 else 块,我相信您想要断言并摆脱传统的 if else 以检查 conditions

代码:

public void findWiki() {
    List<WebElement> TryLink = driver.findElements(By.xpath("//a[@href='https://ru.wikipedia.org/wiki/%D0%A8%D0%BF%D0%B0%D0%B6%D0%BD%D0%B8%D0%BA']"));
    int size = TryLink.size() ;
    assertTrue(size > 0, "try link exists"); 
}

基本上我们使用findElements 并检查大小,如果它是&gt;0 然后在assertTrue. 内部解析就像这样assertTrue(size &gt; 0, "try link exists");

【讨论】:

  • 代码可以工作,但是为什么执行程序“try link exists”后控制台不写。还是什么都不写?我只是一个初学者,我正在尝试详细了解它是如何工作的
  • 只有在失败的情况下才会显示断言中使用的文本。
  • @cruisepandey 我希望我这样做 :)
  • @cruisepandey 100% 同意你的看法
  • 另外,请注意我在代码中使用的findElements,元素永远不会抛出任何异常。它要么有一些网络元素,要么有空列表。这基本上是我们永远不会遇到此类元素异常的原因。
【解决方案2】:

要使您的findWiki() 带有断言,可以按如下方式完成:

public void findWiki() {

    TryLink = chromeDriver.findElement(By.xpath("//a[@href='https://ru.wikipedia.org/wiki/%D0%A8%D0%BF%D0%B0%D0%B6%D0%BD%D0%B8%D0%BA']"));

    assertTrue(TryLink.isDisplayed(),"No link is there"));
}

【讨论】:

  • 这里的actualString 是什么?
  • 如果找不到该元素,它将抛出NoSuchElement异常,然后是assertion failure
  • @cruisepandey 正确。我只是将现有方法翻译为使用断言而不是标题中 OP 要求的 if-else
  • 如果链接出错,不显示错误信息
  • 现在您可以为我们的答案投票并接受其中一个...
猜你喜欢
  • 1970-01-01
  • 2022-11-25
  • 1970-01-01
  • 2020-10-14
  • 2018-09-26
  • 1970-01-01
  • 1970-01-01
  • 2011-02-11
  • 1970-01-01
相关资源
最近更新 更多