jagdpanzer
jagdpanzer

Reputation: 713

Assert a text box is empty in Selenium

I'm currently writing a test and I was wondering if there was a way to assert that a text box is empty.

The test is for a logout command that "clears data" instead of remembering your email or username. The way I modeled this test has the test log in, log out, and the part that I'm stuck at - asserting that the email text box on the login screen is empty after logging out.

I've tried stuff like this:

if (driver.findElement(By.cssSelector("input[type=\"text\"]").equals(""))) {
    // This will throw an exception
}

But that doesn't work because the arguments aren't accepted.

Any ideas?

Upvotes: 3

Views: 11342

Answers (2)

Brian S.
Brian S.

Reputation: 373

The previous answer works, but the assertion can be a lot cleaner. Assertions should always give some reasonable message. Here is an example using the JUnit assertThat and the hamcrest matchers.

import org.junit.Assert;
import static org.hamcrest.Matchers.isEmptyString;
...
WebElement myInput = driver.findElement(By.cssSelector("input[type=\"text\"]"));
Assert.assertThat(myInput.getAttribute("value"), isEmptyString());

Or better yet, give a reason message:

Assert.assertThat("Field should be empty", myInput.getAttribute("value"), isEmptyString());

Upvotes: 3

alecxe
alecxe

Reputation: 473873

I think you need to get the value attribute:

WebElement myInput = driver.findElement(By.cssSelector("input[type=\"text\"]"));

if (!myInput.getAttribute("value").equals("")) {
    fail()
}

Upvotes: 3

Related Questions