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?
I think you need to get the value attribute:
WebElement myInput = driver.findElement(By.cssSelector("input[type=\"text\"]"));
if (!myInput.getAttribute("value").equals("")) {
fail()
}
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());
Related
What is the simplest way to print log output to console when running java program without getting the fortify error Poor Logging Practice: Use of a System Output Stream?
I want to print out few lines so it is displayed after the program is finished. System.out.println isn't accepted as best practice. What other method can I use?
public static void IBanUpdateTest(){
driver.get("http://10.10.10.10/demo-web-1.0-SNAPSHOT"); //define the url
String pageTitle = driver.getTitle(); //get the title of the webpage
System.out.println("The title of this page is ===> " +pageTitle);
Assert.assertEquals("IBan - Business ID code", pageTitle); //verify the title of the webpage
driver.findElement(By.id("0iban")).clear();//clear the input field before entering any value
driver.findElement(By.id("0iban")).sendKeys("5464564654");//enter the IBan Value
driver.findElement(By.id("0businessIdentifierCode")).clear();
driver.findElement(By.id("0businessIdentifierCode")).sendKeys("54645646548546465"); //enter the BIC value
driver.findElement(By.id("0updateRow")).click(); //click Update button
System.out.println("Successfully updated the row");
}
I believe this is the best solution:
Logger logger = LoggerFactory.getLogger(YourClass.class);
It is generally considered a bad practice to log to System.out, Fortify is correctly flagging this. I would not recommend simply ignoring it / turning off the warning.
As others have mentioned in the comments, Spring Boot has the Logback logging library configured by default. You can configure loggers in code, but that just becomes noise after a while, so many find it convenient to add the Lombok library and to use it's #Log annotation to have a logger generated at compile time. Then your code becomes something like:
#Log
public class MyClassThatLogs {
public void myMethod() {
log.info("myMethod was called");
}
}
I'm using Selenium Web Driver with Java. I have the following code:
<div class="missingData">
<p class="notification_text" id="notification_text">Please review the following questions<br></p>
</div>
I have an assertEquals to check if the text is present on the page. It seemed to be running fine, but then I tested the method by putting junk text to test:
assertEquals(driver.findElement(By.id("notification_text")).getText(), "salkjdal");
Unfortunately, the test still passes. What is going on? The junk text is definitely not on the page.
I believe my issue was that I had assertEquals imported from the junit package instead of the testng package. I'm creating TestNG tests so I'm guessing that import caused some issues. I also debugged by making sure I was reading in the string correctly. In my case, I did this:
String abc = driver.findElement(By.id("notification_text")).getText();
The text was what I expected, and if I couldn't figure out the assertEquals issue, I could have also used the basic String.equals() to circumvent the problem in my case.
I'm having a problem with Selenium when it comes to use .sendKeys(text). During the automation process, sometimes selenium is sending incomplete strings to the browser, which causes to create incorrect searchs.
i.e. I want to type "MY DROP", and it will type "Y DROP", or "ROP".
It does not always type the same way, so sometimes 2 letters might be missing, and sometimes the whole word is missing.
This only happens to dropdowns, where I have a specific method that handles the dropdown selection, as we are using angular I can't use the selenium select dropdown method.
I already tried to set Thread.Sleeps and waits on the dropdown selection but nothing seems to work, currently this is what I use to select a value:
public void select(String item) {
waitTillClicable();
WebElement element = getElement();
openDropDown(element);
element.sendKeys(item);
waitResultLoad();
selectResult(element);
}
This code was working perfectly until the last week. I'm thinking it has something to deal with the new Chrome version 45, as before it was not happening. I also tried to use different chromedriver versions, and running on a Linux machine, but nothing seems to have an effect.
Right now I created a workaround where I keep verifying if the string was typed correctly, and re-typing it until it is correct, but this makes the execution time increased, which I wanted to avoid.
Why are you using .sendKeys() to select a value in a SELECT? Use the provided methods for a Select: .selectByIndex(int), .selectByValue(String), or .selectByVisibleText(String). Some examples...
Select test = new Select(driver.findElement(By.id("dropdown")));
test.selectByIndex(1);
test.selectByValue("myValue");
test.selectByVisibleText("VisibleText");
See if the happens on Firefox driver or IE driver
The other thing is the method signature is
public void sendKeys(CharSequence... value)
can you try to send it like this sendKeys( "MY","DROP"); instad and see the result
Hope this may help.
Alan Mehio
London, UK
I am using Selenium RC using Java with eclipse and TestNG framework. I have the following code snippet:
assertTrue(selenium.isTextPresent("Please enter Email ID"));
assertTrue(selenium.isTextPresent("Please enter Password"));
First assertion was failed and execution was stopped. But I want to continue the further snippet of code.
I suggest you to use soft assertions, which are provided in TestNg natively
package automation.tests;
import org.testng.asserts.Assertion;
import org.testng.asserts.SoftAssert;
public class MyTest {
private Assertion hardAssert = new Assertion();
private SoftAssert softAssert = new SoftAssert();
}
#Test
public void testForSoftAssertionFailure() {
softAssert.assertTrue(false);
softAssert.assertEquals(1, 2);
softAssert.assertAll();
}
Source: http://rameshbaskar.wordpress.com/2013/09/11/soft-assertions-using-testng/
Selenium IDE uses verify to perform a soft assertion, meaning that the test will continue even if the check fails and either report the failures at the end of the test or on the event of a hard assertion.
With TestNG it is possible to have these soft assertions by using custom test listeners. I have documented how to do this on my blog: http://davehunt.co.uk/2009/10/08/using-soft-assertions-in-testng.html
Basically, you need to create your own verify* methods, in these you can catch assertion failures and add them to a map. Then in a custom afterInvocation listener you can set the test to failed if the map is not empty.
I am adding again one of the easiest ways to continue on assertion failure. This was asked here.
try{
Assert.assertEquals(true, false);
}catch(AssertionError e)
{
System.out.println("Assertion error. ");
}
System.out.println("Test Completed.");
Change your assertions to verifications:
verifyTrue(selenium.isTextPresent("Please enter Email ID"));
verifyTrue(selenium.isTextPresent("Please enter Password"));
Once an assertion fails, execution should stop, that's the point of using them.
You can declare an assertion that tests both things, but then you're testing two things at once. Better to fix the cause of the first failure, then move on to the second assertion.
I'm trying to use StrutsTestCase for testing my Struts2 actions, but I'm getting always the "error" value back while executing the "execute()" method from the proxy. Here's the example:
public void testSpike() throws Exception{
request.addHeader("param1", "param");
ActionProxy proxy = getActionProxy("/action/to/test.action");
assertNotNull(proxy);
TestAction action = (TestAction) proxy.getAction();
assertNotNull(action);
String output = proxy.execute();
}
the output string is always "error". Is there a way to understand what happened there? The logs are not saying anything, and even trying to debug placing a breakpoint on the Action class doesn't help (the code never stops there).
Any suggestions?
Thanks
Roberto
Add a breakpoint at the line 'String output = proxy.execute();'. Execute your test in debug mode in your favorite IDE and step through the code to realize why execute() method returns always 'error'.