Printing a message that element is not present in catch block, selenium - java

This is my Feature file:
#Done #ProdSmoke #KioskSmoke
Scenario Outline: Add Items to the Cart and click Cancel
Given Open the application on Tablet device
When Click on the KeyInItem button
Then Enter Item Number "<upc>"
And Click Cancel
And Item "not added" in the cart
Examples:
| upctype | upc|
| upca | 8 |
This is my stepdef file:
#And("^Item \"([^\"]*)\" in the cart$")
public void itemAddedInTheCart(String action) throws Exception {
addItem.verify_itemadded(action);
}
And this is my function verify_itemadded(action):
public void verify_itemadded(String action) throws Exception {
try {
if (action.equals("added") && element("ItemVerify").isDisplayed()) {
Assert.assertTrue(element("ItemVerify").isDisplayed());
logger.info("Item Added");
}
}
catch (Exception ex)
{
if(action.equals("not added") && !element("ItemVerify").isDisplayed())
logger.info("Item not added");
}
}
Even though the test is passing, I am unable to get the message "item not added".
Any ideas?

You need to update the code as below. Let me know if you face any issue.
try
{
boolean isItemVerified = element("ItemVerify").isDisplayed());
if (action.equals("added") && isItemVerified )
{
logger.info("Item Added");
}
Assert.assertTrue(isItemVerified);
}
catch(AssertionError ae)
{
logger.info("Item not added");
}

Related

ParseServer: not saving user info?

Basically, if a user is located near a certain event, I want to update an attribute called "pending" to "yes". I'm using a for loop to iterate through all the users (this code is just for a demo purposes, there aren't that many users), and check their distance to the specified event. If they are <= 7000 away, then I want to update "pending" to "yes." However, none of the attributes are actually saving?
I have attached my whole code but the relevant snippet occurs after this comment:// ****** NOTIFICATIONS FOR USERS WHO LIVE IN THE NEIGHBOURHOOD ***********
THINGS I KNOW:
the first log statement I put "numUsers" returns how many users are in the query, for me to validate that all of the users are actually queried. It returns 7, which is true! So that works.
IN the for loop, it's successfully printing each users user name at each iteration, so I know it's properly iterating through the users.
lastly, at u.SaveInBackground(....) it's successfully printing out each users name, and "yes" if they are within the distance I specified, or "null" if not.
but when I check the server none of this information is actually stored?
And outside of this method if I try to get any user's "pending" attribute, it will tell me it's null.
I've been stuck on this for hours now!
public void onButtonClickDecision(final View view) {
ParseQuery<ParseObject> query = ParseQuery.getQuery("IncidentReports");
query.whereEqualTo("reference", intent.getStringExtra("reference"));
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(final List<ParseObject> objects, ParseException e) {
if (e == null) {
if (objects.size()>0) {
//if we clicked, decline -> update status to decline
if (view.getId() == R.id.decline) {
objects.get(0).put("status", "declined");
}
// if we clicked approve -> update status to approve
else if (view.getId() == R.id.approve) {
// update status
objects.get(0).put("status", "approved");
// ****** NOTIFICATIONS FOR USERS WHO LIVE IN THE NEIGHBOURHOOD ***********
ParseQuery<ParseUser> query3 = ParseUser.getQuery();
query3.findInBackground(new FindCallback<ParseUser>() {
#Override
public void done(List<ParseUser> users, ParseException e) {
Log.i("numUsers", Integer.toString(users.size()));
if ( e== null && users.size()>0) {
// COMPARE EACH USERS ADDRESS
for (final ParseUser u : users) {
Log.i("user name", u.getUsername());
String address = u.getString("address");
try {
// sets up users home as a Location
List<Address> list = geocoder.getFromLocationName(address, 1);
Address add = list.get(0);
Location home = new Location(LocationManager.GPS_PROVIDER);
home.setLatitude(add.getLatitude());
home.setLongitude(add.getLongitude());
// check if user is located in incident neighbourhood
if (home.distanceTo(incidentLoc) <= 7000) {
u.put("pending", "yes");
}
} catch (IOException ex) {
Log.i("ApprovedCheckingUsers", "failed");
System.out.println(ex.getMessage());
}
u.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
Log.i("Updated:", u.getUsername() + "," + u.getString("pending"));
}
});
}
}
}
});
}
// NOTIFY USER WHO POSTED
objects.get(0).put("notified", "false");
objects.get(0).put("reviewedby", ParseUser.getCurrentUser().getString("username"));
objects.get(0).saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
System.out.println("Saving status updates");
currentStatus.setText(objects.get(0).getString("status"));
Toast.makeText(ViewIndividualReport.this, "Status successfuly changed", Toast.LENGTH_SHORT).show();
} else {
System.out.println("Failed to save");
Toast.makeText(ViewIndividualReport.this, "Could not update status at this time. Try again later.", Toast.LENGTH_SHORT).show();
}
}
});
}
}
}
});
}

What is wrong with my JTextField here? (details in text)

EDIT: Basically the UI class sends #login to the client, the client sends it to the server, the server sends back "#login" to the client indicating successful log-in and the client sends the "#login" along to the UI via UI.display()
Apologies for bad grammar/formatting.
Here's the most relevant block of code, with explanation to follow:
else if (e.getSource() == this.loginButton)
{
if (this.soundON == true)
{
this.clickSound.play();
}
this.client.handleMessageFromClientUI("#login "+this.loginField.getText());
this.client.handleMessageFromClientUI("#balance");
this.client.setLoginID(this.loginField.getText());
if (this.loggedIn)
{
this.loginButton.setEnabled(true);
this.note.setText("Account Screen");
this.status.setText("Logged in to: "+this.client.getLoginID());
this.mainDisplay.removeAll();
this.controlBar.removeAll();
this.mainDisplay.add(Box.createRigidArea(new Dimension(0,30)));
this.mainDisplay.add(this.title);
this.mainDisplay.add(Box.createRigidArea(new Dimension(0,50)));
this.mainDisplay.add(Box.createRigidArea(new Dimension(100,0)));
this.mainDisplay.add(this.balanceLabel);
this.mainDisplay.add(Box.createRigidArea(new Dimension(0,110)));
this.controlBar.add(debitButton);
this.controlBar.add(creditButton);
this.controlBar.add(quitButton);
this.repaint();
}
else
{
JOptionPane.showMessageDialog(null, "Log-in Failed.", "alert", JOptionPane.ERROR_MESSAGE);
}
}
public void display(String msg)
{
if (msg.startsWith("#LOGIN"))
{
this.loggedIn = true;
}
else if (msg.startsWith("#BALANCE"))
{
this.balanceLabel.setText("Balance: $"+msg.substring(43));
this.repaint();
}
else if (msg.startsWith("#ALERT"))
{
JOptionPane.showMessageDialog(null, msg.substring(7), "Server Message", JOptionPane.PLAIN_MESSAGE);
}
else
{
//JOptionPane.showMessageDialog(null, msg, "Server Message", JOptionPane.INFORMATION_MESSAGE); //For debugging
}
}
This is just part of the class, here's the rest: http://pastebin.com/3f99eFWk
My problem is in actionPerformed(ActionEvent e) in the loginButton case. It always goes to this Block once initially when the button is clicked:
else
{
JOptionPane.showMessageDialog(null, "Log-in Failed.", "alert", JOptionPane.ERROR_MESSAGE);
}
then if I click the button again it works and goes to the if (this.loggedIn) case block. loggedIn=true is obtained when This line is executed:
this.client.handleMessageFromClientUI("#login "+this.loginField.getText());
which in turn calls:
public void handleMessageFromClientUI(String message)
{
else
{
try
{
sendToServer(message);
}
catch(IOException e)
{
clientUI.display("Could not send message to server.");
//quit();
}
}
}
Which calls server.handleMessageFromClient(Object msg, Connection client) that has the following relevant code in it:
try
{
client.sendToClient("#LOGIN Logging in to account: "+tempStr);
}
catch (IOException e)
{
System.out.println("Failed to send message to client");
}
client.setInfo("loginID", tempStr);
I know it doesn't fail to send, I've tested it out. The problem is why does the if statement in actionPerformed fail the first time the button is pressed even though the text is typed in the textfield, then passes the second time??

If-Else condition is not working for my test case

I am writing an if-else condition in my test case. But function not going in else condition , it just look for if (condition).I am not able to figure out the problem.
Using java with selenium webdriver
public static void afterMenthod() throws InterruptedException {
try {
if (remoteDriver.findElementByName("Confirmation").isDisplayed())
{
if (remoteDriver.findElementByName("Stop").isDisplayed())
{
remoteDriver.findElementByName("Stop").click();
}
else
{
remoteDriver.findElementByName("Resume").click();
remoteDriver.findElementByName("Navigate up").click();
remoteDriver.findElementByName("Stop").click();
}
}
else if (remoteDriver.findElementByName("TRY AGAIN").isDisplayed())
{
System.out
.println("There is some problem in deposit transaction");
remoteDriver.findElementByName("Navigate up").click();
remoteDriver.findElementByName("Stop").click();
remoteDriver.findElementByName("Stop").click();
}
else if (remoteDriver.findElementByName("NEXT").isDisplayed() || remoteDriver.findElementByName("SUBMIT").isDisplayed() )
{
System.out.println("There is some problem in deposit transaction");
remoteDriver.findElementByName("Navigate up").click();
remoteDriver.findElementByName("Stop").click();
}
else {
// if(remoteDriver.findElementByName("namaskaar").isDisplayed())
System.out
.println("There is some problem in deposit transaction");
}
} finally{
GeneralMethods.signout();
System.out.println("Script Over");
}}
It just look for "confirmation" element, if it does not find that test get fails.
Try checking whether the element is displayed AND enabled
WebElement confirmation = remoteDriver.findElementByName("Confirmation");
if ( confirmation.isDisplayed() && confirmation.isEnabled()) {
...
}
else {
...
}
Write Your Else Part In catch block.
This way if an exception occurs, your else block will get executed.
It worked for me.
My Code to find a element in scroll-able screen and click it.
public static void scrollToBeFound(String Value) throws InterruptedException{
try{
driver.findElementByName(Value).click();
Thread.sleep(5000);
}
catch(Exception e){
try{
driver.swipe(120,420,120,750,1500);
Thread.sleep(3000);
driver.findElementByName(Value).click();
}
catch(Exception ex){
driver.swipe(120,750,120,420,1500);
Thread.sleep(3000);
driver.findElementByName(Value).click();
}
}
}
"It just look for "confirmation" element, if it does not find that test get fails." - that's because findElementByName throws an exception if element is not found. Which is why the else is not getting processed. You need to use try-catch-finally in your code. Search any forum on how to use it.

problems with the 2 options joption

I'm having problems with these 2 different options, the first one opens up just fine to a browser for future use, but the second option opens the browser and not the dialogue in which i'd like to have open. Also can someone tell me how to make the cancel button cancel out and not open the browser, thanks in advance here's the code.
public static void CheckForUpdates(){
Object[] possibleValues = { "Check for Updates", "Check for version ID" };
Object selectedValue = JOptionPane.showInputDialog(null,
"What would you like to do?", "",
JOptionPane.INFORMATION_MESSAGE, null,
possibleValues, possibleValues[0]);
if ( JOptionPane.YES_NO_OPTION == JOptionPane.YES_OPTION) {
try {
Desktop.getDesktop().browse(new URI("www.google.ca"));
} catch (IOException | URISyntaxException e) {
}
if ( JOptionPane.YES_NO_OPTION == JOptionPane.NO_OPTION){
JOptionPane.showMessageDialog(frame, "version ID: V1");
}
}
}
Comparing constants is deterministic, i.e. you don't get any variation in behavior.
You need to check the result of showInputDialog which is an Object value. The value is null when nothing (cancel) is selected.
if (selectedValue != null) { // anything selected?
// Check for version ID?
if (selectedValue.toString().equals(possibleValues[1])) {
JOptionPane.showMessageDialog(null, "version ID: V1");
} else {
try {
Desktop.getDesktop().browse(new URI("www.google.ca"));
} catch (IOException | URISyntaxException e) {
}
}
}
Aside: Java naming conventions show that method names start with an lowercase letter such as checkForUpdates.

How can I launch an Eclipse command from Java?

How do I launch a find and replace command without the user clicking edit->find replace or ctrl+F? I need to do this with a plug-in written in Java.
The action that launches the dialog is FindInFileActionDelegate (it has a few sister types for different scopes), this is found in the org.eclipse.search plugin.
The delegates all inherit from a common parent called RetrieverAction. The RetrieverAction's run() method shows the dialog and runs the query. You can take the relevant processing from this method. You may need to register as an ISelectionListener to track the active selection.
public void run() {
IWorkbenchPage page= getWorkbenchPage();
if (page == null) {
return;
}
TextSearchQueryProvider provider= TextSearchQueryProvider.getPreferred();
String searchForString= getSearchForString(page);
if (searchForString.length() == 0) {
MessageDialog.openInformation(getShell(), SearchMessages.RetrieverAction_dialog_title, SearchMessages.RetrieverAction_empty_selection);
return;
}
try {
ISearchQuery query= createQuery(provider, searchForString);
if (query != null) {
NewSearchUI.runQueryInBackground(query);
}
} catch (OperationCanceledException ex) {
// action cancelled
} catch (CoreException e) {
ErrorDialog.openError(getShell(), SearchMessages.RetrieverAction_error_title, SearchMessages.RetrieverAction_error_message, e.getStatus());
}
}

Categories