【问题标题】:Why am I getting AssertionError in Selenium?为什么我在 Selenium 中收到 AssertionError?
【发布时间】:2019-01-13 09:06:03
【问题描述】:

您能否建议,当测试运行正常,但在测试结束时在 Selenium 中出现错误和长堆栈跟踪时,我们能做些什么?

package com.example.tests;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;

import java.util.NoSuchElementException;
import java.util.concurrent.TimeUnit;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.NoAlertPresentException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class AddGroupTests {
  private WebDriver driver;
  private boolean acceptNextAlert = true;
  private StringBuffer verificationErrors = new StringBuffer();

  @Before
  public void setUp() throws Exception {
    System.setProperty("webdriver.chrome.driver","C:\\selenium-java-3.12.0\\chromedriver.exe");
    driver = new ChromeDriver();
    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
  }

  @Test
  public void testAddNewGroup() throws Exception {
    openMainPage();
    findFrame();
    logIn();
    goToGroupPage();
    fillFormAndSubmit("Group1", "Head", "Foot");
    verifyTextOnPage();
    returnToGroupsPage();
  //Once all your stuff done with this frame need to switch back to default
    driver.switchTo().defaultContent();
  }

  @Test
  public void testAddNewEmptyGroup() throws Exception {
    openMainPage();
    findFrame();
    logIn();
    goToGroupPage();
    fillFormAndSubmit("", "", "");
    verifyTextOnPage();
    returnToGroupsPage();
  //Once all your stuff done with this frame need to switch back to default
    driver.switchTo().defaultContent();
  }

private void verifyTextOnPage() {
    try {
      assertEquals("A new group has been entered into the address book.return to the group page", driver.findElement(By.xpath("//div[@id='content']/div")).getText());
    } catch (Error e) {
      verificationErrors.append(e.toString());
    }
}

private void returnToGroupsPage() {
    driver.findElement(By.linkText("group page")).click();
}

private void fillFormAndSubmit(String name, String header, String footer) {
    clickAndClear("group_name", "group_name");
    driver.findElement(By.name("group_name")).sendKeys(name);
    clickAndClear("group_header", "group_header");
    driver.findElement(By.name("group_header")).sendKeys(header);
    clickAndClear("group_footer", "group_footer");
    driver.findElement(By.name("group_footer")).sendKeys(footer);
    driver.findElement(By.name("submit")).click();
}

private void goToGroupPage() {
    driver.findElement(By.linkText("Группы")).click();
    driver.findElement(By.name("new")).click();
}

private void logIn() {
    driver.findElement(By.name("user")).clear();
    driver.findElement(By.name("user")).sendKeys("admin");
    driver.findElement(By.name("pass")).clear();
    driver.findElement(By.name("pass")).sendKeys("pass");
    driver.findElement(By.xpath("//input[@value='Войти']")).click();
}

private void findFrame() {
        WebDriverWait wait = new WebDriverWait(driver, 10);
        wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt("demobody"));
}

private void openMainPage() {
    driver.get("https://www.softaculous.com/softaculous/demos/PHP_Address_Book");
}

private void clickAndClear(String locator, String locator2) {
    driver.findElement(By.name(locator)).click();
    driver.findElement(By.name(locator2)).clear();
}

  @After
  public void tearDown() throws Exception {
    driver.quit();
    String verificationErrorString = verificationErrors.toString();
    if (!"".equals(verificationErrorString)) {
      fail(verificationErrorString);
    }
  }

  @SuppressWarnings("unused")
private boolean isElementPresent(By by) {
    try {
      driver.findElement(by);
      return true;
    } catch (NoSuchElementException e) {
      return false;
    }
  }

  @SuppressWarnings("unused")
private boolean isAlertPresent() {
    try {
      driver.switchTo().alert();
      return true;
    } catch (NoAlertPresentException e) {
      return false;
    }
  }

  @SuppressWarnings("unused")
private String closeAlertAndGetItsText() {
    try {
      Alert alert = driver.switchTo().alert();
      String alertText = alert.getText();
      if (acceptNextAlert) {
        alert.accept();
      } else {
        alert.dismiss();
      }
      return alertText;
    } finally {
      acceptNextAlert = true;
    }
  }
}

堆栈跟踪是这样的:

java.lang.AssertionError: org.junit.ComparisonFailure: expected:<...to the address book.[]return to the group ...> but was:<...to the address book.[
]return to the group ...>
    at org.junit.Assert.fail(Assert.java:88)
    at com.example.tests.AddGroupTests.tearDown(AddGroupTests.java:112)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.base/java.lang.reflect.Method.invoke(Unknown Source)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:33)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
    at org.junit.vintage.engine.execution.RunnerExecutor.execute(RunnerExecutor.java:42)
    at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.accept(Unknown Source)
    at java.base/java.util.stream.ReferencePipeline$3$1.accept(Unknown Source)
    at java.base/java.util.Iterator.forEachRemaining(Unknown Source)
    at java.base/java.util.Spliterators$IteratorSpliterator.forEachRemaining(Unknown Source)
    at java.base/java.util.stream.AbstractPipeline.copyInto(Unknown Source)
    at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(Unknown Source)
    at java.base/java.util.stream.ForEachOps$ForEachOp.evaluateSequential(Unknown Source)
    at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(Unknown Source)
    at java.base/java.util.stream.AbstractPipeline.evaluate(Unknown Source)
    at java.base/java.util.stream.ReferencePipeline.forEach(Unknown Source)
    at org.junit.vintage.engine.VintageTestEngine.executeAllChildren(VintageTestEngine.java:83)
    at org.junit.vintage.engine.VintageTestEngine.execute(VintageTestEngine.java:74)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:170)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:154)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:90)
    at org.eclipse.jdt.internal.junit5.runner.JUnit5TestReference.run(JUnit5TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:538)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:760)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:460)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:206)

尝试删除所有导入并一一修复红色问题,仍然存在故障。我看到消息:AssertionError,但无法定位问题。有什么建议?提前致谢

【问题讨论】:

  • 你能分享一下实际的错误信息吗?
  • 您正在尝试导入一个类的所有元素。您只能对静态导入或包执行此操作。
  • 发布minimal reproducible example。请don't post screenshots of code。粘贴代码并正确格式化它。发布实际(完整)错误消息。
  • 看起来您正在使用 Eclipse。删除所有导入。现在,您将在 Eclipse 无法识别的代码下看到许多红色波浪线。将鼠标悬停在一个上,您将看到一个带有快速修复的弹出窗口。单击导入相关库的快速修复。继续此过程,直到所有红色曲线消失。
  • 您应该尝试调试您的 tearDown() 方法,因为查看您的屏幕截图时存在堆栈跟踪问题,并且在此添加行之后会导致您的问题出现此异常以获得正确答案。

标签: java selenium


【解决方案1】:

AssertionError 发生在断言(您要验证的东西)失败时。当您收到AssertionError 时,并不意味着您的代码失败,而是意味着您检查的条件不正确。

现在通常断言错误意味着你正在测试的东西有问题。但通常是因为您测试事物的方式有问题。

在您的示例中,堆栈跟踪很有帮助:

java.lang.AssertionError: org.junit.ComparisonFailure: expected:<...to the address 
book.[]return to the group ...> but was:<...to the address book.[
]return to the group ...>

您尝试比较两个字符串,但它们不同。有什么不同?它突出显示:在您预期的字符串中(verifyTextOnPage 测试中的"A new group has been entered into the address book.return to the group page"),“return”紧跟在点之后,没有空格。实际文本显然在它们之间有一个换行符(“return”继续在新行上)。这就是比较失败的原因,这就是您得到AssertionError 的原因。

请不要害怕错误消息并尝试理解它们:它们提供了有价值的信息。

【讨论】:

    猜你喜欢
    • 2022-07-01
    • 2019-07-24
    • 1970-01-01
    • 2020-09-19
    相关资源
    最近更新 更多