I'm sending a username and password to a website for authentication purposes, after all is said and done and I've retrieved the results from the server, I've placed the results in a variable called 'response' To this point everything is working correctly
response = sb.toString();
Toast.makeText(this,"Returned Value: "+ response,0).show();
The value seen in the above Toast is the value being returned by the php script. I've used both a valid user and an invalid user and the Toast displayed above shows the correct value (i.e. "Good Login" or "Login Failed") returned by the server. I want to test for those results so I can start the appropriate activity so I've put in some test "if" statements
if("Good Login".equals(response)){
Toast.makeText(this, "Registered User" + mUsername, 0).show();
}
if("Login Failed".equals(response)){
Toast.makeText(this, "Sorry You're Not A Registered Subscriber",0).show();
}
I'm getting nothing from either one.
I've also tried
if(response.equals("Good Login")){
Toast.makeText(this, "Registered User" + mUsername, 0).show();
}
if(response.equals("Login Failed")){
Toast.makeText(this, "Sorry You're Not A Registered Subscriber",0).show();
}
With the same results. Not sure what else to test for. Is there a better way to test for success or failure?
Thanks
Debug (or print) the exact value of the response variable.
It is likely that there are whitespaces, so you may need to have response = response.trim()
I would return an integer error code rather than some string to check the error response.
Make sure you are returning the correct case, otherwise use equalsIgnoreCase
The Java string equals function is fully case/spacing sensitive compare.
So if:response = "Good Login " or if it contains extra-spaces or non-printing characters then it will fail the test.
It would be a good idea to strip all whitespace, even the internal ones. Here's a SO question about doing just that. Also use String.equalsCaseInsesitive() when doing that actual comparison.
Related
I'm writing some Selenium UI automation tests and I'm currently working on a section where multiple validation messages can appear depending on the response from source system. I have several different messages to trigger.
Every time the error message is shown on the UI it will sit in the following element but the text string changes each time depending on what the message is while the id and class remain the same:
<span id="lblErrorText" class="validationError">
"My error message will appear here"
</span>
In my page object class I am defining my fields before I use them in a method. So I have the following:
By errorMessage = By.xpath("//span[#class='validationError']");
I then use errorMessage in a method to return it as a boolean to enable me to assert against. As follows:
public boolean getInvalidRefNumberErrorMessage(){
return driver.findElements(errorMessage).contains("My error message will");
}
But every time I run my test I see that method getInvalidRefNumberErrorMessage is returning a FALSE.
I've tried using the id instead but no luck. I've never had to validate a dynamic message before so I'm a bit stuck here.
Seems your code has some wrong places if they are not copy/paste mistake.
Should use findElement, not findElements which return a List.
Should call getText() to return the message content as String, then call String.contains()
public boolean getInvalidRefNumberErrorMessage(){
return driver.findElement(errorMessage).getText()
.contains("My error message will");
}
I have a scenario in which clicking on "Save" button can give three different alerts based on the data entered. It can give "Saved successfully", "User already registered" and "Username already exist" alerts. I have tried:
driver.findElement(By.id("dnn_ctr5995_View_btnsavesession")).click();
Thread.sleep(10000);
Alert alert = driver.switchTo().alert();
String A = alert.getText();
if (A == "Username already exist"){
System.out.println("Admission number already exist.");
alert.accept();
} else if (A == "User already registered"){
System.out.println("User already registered");
alert.accept();
} else if (A == "Saved Successfully."){
System.out.println("Saved Successfully.");
alert.accept();
}
But it is showing No Alert present exception. I have tried increasing the sleep time but still it shows the same exception.
I'm guessing you never actually call alert.accept() because you're using A == "User already registered" instead of "User already registered".equalsIgnoreCase(A). If you change the if conditions, that should fix your problem.
As per the Html shared, the id of the element is not "save". So the first line of the shared code should be modified a bit to achieve the output.
Change the element identification tag to :
driver.findElement(By.id("dnn_ctr5995_View_btnsavesession")).click();
or if the 'id' of the element is changing on every instance, then it can be changed to:
driver.findElement(By.xpath("//*[contains(#id,'_View_btnsavesession')]")).click();
Looks like your clicking is not actually clicking because the 'save' id is no like in the element.
Try to do it like this:
driver.findElement(By.cssSelector("[id*=save"])).click();
And then trying to catch the alert. Please note the '*' in selector.
I am testing a web application and my sample test case has three steps:
Enter Username
Enter Password
Click 'Login'
driver.findElement(By.id("username")).sendKeys(username);
driver.findElement(By.id("password")).sendKeys(password);
driver.findElement(By.id("LoginButton")).click();
I need to generate a report which specifies which steps passed and which failed. Is there some mechanism by which I can know that each of those lines executed successfully? Does Selenium have some kind of inbuilt Activity/Event Listener?
If you want log all basic steps like click, navigate, on find element, etc
I recommend you add some event listener. You can use the class EventFiringWebDriver.
An example:
EventFiringWebDriver events = new EventFiringWebDriver(this._driver);
events.Navigated += new EventHandler<WebDriverNavigationEventArgs>(eventAfterNavigate);
and you can define the event handler as
private void eventAfterNavigate(object sender, WebDriverNavigationEventArgs e)
{
Log("URL visited: " + e.Driver.Url); // Call to your favourite log method
}
You can find more possible event handlers in the Webdriver API reference: http://selenium.googlecode.com/svn/trunk/docs/api/dotnet/html/AllMembers_T_OpenQA_Selenium_Support_Events_EventFiringWebDriver.htm
You may use either Verify or Assert to be sure that something is present or absent on the page. Verify will return you Boolean and continue running while Assert on false will stop you test(s).
In this particular case you may verify that you typed username into element with id=username. So your code could look like this:
driver.findElement(By.id("username")).sendKeys(username); // this will enter username
assertEquals(selenium.getValue("id=username"), username); // this will check that text in your username field is 'username' (also you may use Assert.IsTrue)
As far as I know there is verifyTextPresent in Selenium 2 Webdriver, so you may use this:
try
{
assertEquals(selenium.getValue("id=username"), username); // put message into your log: success
}
catch (Exception)
{
// put message into your log: failed
}
I suggest to verify Button click but waiting for some notification that you logged in: e.g. text "Hello, {username}" might appear, or new element (absent before log in) might appear as well. So if this element is present - you are definitely logged in.
If you want to see if each step is successful, then I put some asserts (depending on your unit testing framework) to verify that the steps succeeded.
For example, to check that the username field actually received input, you could immediately verify that the username field has the text of whatever the username is that was typed in.
Some pseudo code:
IWebElement element = driver.findElement(By.id("username"));
element.sendKeys(username);
assertsEquals(username, element.text);
Likewise, to verify that a click was successful, you could check and assert that an element that is expected on the next page exists, which would then indicate that the login was successful.
If Selenium dose not throw Exception then lines are executed successfully.
But question is how do you define success? I would check site that was loaded after click on LoginButton to be sure that behavior of web application is like you expect.
I wrote an HTTP request in JMeter which creates a Profile with a new Profile ID( which I am passing as a parameter in URL)
I want to generate a new profileID, in case if the given ProfileID is already existed.
How can I do this in JMeter?
currently test runs and passes with showing message that "Profile ID is already existed" as a result, in case of already existed ID.
Don't get Idea how to solve this issue .If I use "if controller", it will check pre-execution condition while I have a post-execution condition that the test runs and after getting this message "already existed" on page it should generate a new ID.
Any help would highly be appreciated.
You can do the following:
While Controller with condition: ${IdExisted} != "Profile ID is already existed"
HTTP Request generating random profile Id
Regular Expression Extractor with reference name IdExisted, regex like "Profile ID is already existed", default value NOT_FOUND
You can carry out "Profile ID is already existed" to User Defined Variables to DRY this test.
But I think, you really don't need While Controller and Regular Expression Extractor. Maybe, you can just make HTTP Request generate more random Id.
To generate random id you can use function:
Random if it should be an int, e.g. ${__Random(1, 100000000)}
RandomString if it should be a string, e.g. ${__RandomString(10)}
How would you go about checking to see if a particular WebElement has been updated?
I have a test that performs a form save and then the UI returns a success/error message.
I am doing a series of saves and I need to test and see if the message is what is expected.
Selenium goes so fast that the browser does not have a chance to catch up.
This is the code that I have for testing for an error message (There is an equivalent success message function as well)
public void assertErrorMessage(String errorMsg) {
// set the wait time a bit so the page can load.
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
List<WebElement> results = driver.findElements(By.xpath("//div[#id='lift__noticesContainer__']/descendant::*"));
boolean success = false;
String message = "";
for (WebElement result : results) {
String id = result.getAttribute("id");
if (id.contains("___error")) {
success = true;
}
if (result.getTagName().equals("li")) {
message += result.getText().trim();
}
}
Assert.assertTrue(success, "No error message generated");
Assert.assertTrue(message.equals(errorMsg), "Expecting message: \"" + errorMsg + "\" but got \"" + message + "\"");
}
As this is written, this looks for the presence of a particular <div> and checks to see if contains certain attributes. If it does, get the message.
The thing is, this will always be true and hence my tests are failing since the message is different than the previous one, but the UI hasn't caught up to where selenium is.
My solution so far to force a Thread.sleep(2000) to just pause a bit to allow for the UI to catch up. I know that it is frowned upon to use Thread.sleep().
i.e. (pseudo-code)
page.setField("value");
page.save();
Thread.sleep(2000);
page.assertErrorMessage("Error message");
Is there any way let me check to see if a WebElement has been updated? If so, I could use the Selenium waits to test for that.
Or perhaps someone else has a suggestion for how to do this?
Thanks in advance.
If the result displayed keeps getting every time you perform page.save().
The best way to make sure that your code waits for the browser to update the message is by using the WebDriverWait object.
A simple example would be -
new WebDriverWait(driver, 10).until(ExpectedConditions.textToBePresentInElement(By.xpath("xpath"), "message"));
You can check if that particular element has the message you are looking for. If that message is not present even after 10 seconds then a TimedOutException will be thrown.
You can check out more variations on the ExpectedConditions as suitable in your situation. Hope this helps you.