Search code examples
javaselenium-webdrivercucumberbddassert

Cucumber TestNG Assert fails with java.lang.NumberFormatException


I'm using a simple Maven project. Whenever I run the assert in cucumber, it fails. but when I run in a normal project, works flawlessly.

Error: java.lang.NumberFormatException: For input string: ""

My Dependency:

<dependencies>
    <!-- https://mvnrepository.com/artifact/io.cucumber/cucumber-java -->
    <dependency>
        <groupId>io.cucumber</groupId>
        <artifactId>cucumber-java</artifactId>
        <version>4.2.2</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/io.cucumber/cucumber-testng-->
    <dependency>
        <groupId>io.cucumber</groupId>
        <artifactId>cucumber-testng</artifactId>
        <version>4.2.2</version>
    </dependency> 
</dependencies>

My Code:

@Then("the cart badge should be updated")
public void theCartBadgeShouldBeUpdated() throws InterruptedException {
    String text = driver.findElement(By.xpath("//span[@id='mat-badge-content-0']")).getText();
    Thread.sleep(3000);
    Assert.assertEquals(Integer.parseInt(text)>0, true);
    driver.quit();
}

I tried to update the jars to the latest version, but I get errors in my project. Do I need to update the jars to any specific version to solve the problem?


Solution

  • If I were to guess... the error is thrown when you parse text to an int on this line,

    Assert.assertEquals(Integer.parseInt(text) > 0, true);
                        ^^^^^^^^^^^^^^^^^^^^^^
    

    and it's because text is coming back as empty string. I'm guessing that's because the page isn't fully loaded. I would suggest you get rid of the sleep that's after the .findElement() (???) and add a WebDriverWait for visible before you pull the text from the element.

    I would update:

    1. Add a WebDriverWait for visible before .getText().
    2. If you are finding an element by an ID, use By.id() instead of By.xpath().
    3. Remove the sleep, it's a bad practice and slows down your tests.
    4. Since you are asserting that something is true, use Assert.isTrue().
    5. Always add a string comment to your asserts... it makes it easier to determine what's being tested when an assert fails.

    Updated code

    @Then("the cart badge should be updated")
    public void theCartBadgeShouldBeUpdated() throws InterruptedException {
        String text = new WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.visibilityOfElementLocated(By.id("mat-badge-content-0"))).getText();
        Assert.isTrue(Integer.parseInt(text) > 0, "Verify that the number in the cart badge is not zero.");
        driver.quit();
    }