How to Implement Conditionally Running of Tests in TestNG? - selenium-webdriver

I am stuck in a scenario, where user is allowed to rate the movie only once a day with same user credentials.
If user tried to rate the same movie or contract, error pop_up seen.
I want to Implement in a way, that if once any movie/contract is rated. The rating functionality should be skipped and Error pop should be Handled.
I am using Selenium eclipse 2017, Chrome browser 61.0 and Test-Ng
Please help in the same.
Thanks.
public class Ratings {
String driverPath = "F:/ChromeDriver/chromedriver.exe";
public WebDriver driver;
public Alert alert;
#BeforeTest
public void LaunchBrowser () throws InterruptedException {
System.out.println("WebBrowser open");
System.setProperty("webdriver.chrome.driver","F:/ChromeDriver/chromedriver.e
xe");
driver = new ChromeDriver();
driver.manage().window().maximize();
}
#Test (priority = 1, alwaysRun = true)
public void HomePageUSA() throws InterruptedException {
driver.navigate().to("Https://us.justdial.com");
String expectedTitle = "Justdial US";
String actualTitle = driver.getTitle();
try
{
AssertJUnit.assertEquals(expectedTitle, actualTitle);
System.out.println("Test Passed");
}
catch (Throwable e)
{
System.out.println("Test Failed");
}
Thread.sleep(3000);
}
#Test (priority = 2, dependsOnMethods = {"HomePageUSA"})
public void Login() throws Exception{
Thread.sleep(3000);
driver.findElement(By.xpath("/html/body/div/div[1]/div[1]/div[1]/div/div/div
/div[4]/aside/div/span/a[1]")).click();
driver.findElement(By.id("inputPassword3")).clear();
driver.findElement(By.id("inputPassword3")).sendKeys("testing.testjd#gmail.c
om");
driver.findElement(By.id("exampleInputPassword1")).clear();
driver.findElement(By.id("exampleInputPassword1")).sendKeys("justdial");
driver.findElement(By.xpath("/html/body/div[4]/div[2]/div[1]/section/div/div
[1]/div/form/div[3]/div/button")).click();
Thread.sleep(1000);
String expectedTitle = "Justdial US";
String actualTitle = driver.getTitle();
try
{
Assert.assertEquals(expectedTitle, actualTitle);
System.out.println("Login Successful");
}
catch (Throwable e)
{
System.out.println("Login Failed");
}
Thread.sleep(1000);
driver.findElement(By.xpath(".//*[#id='us-jdnew-
wrapper']/div[1]/div/header/div/div[1]/a[2]")).click();
Thread.sleep(2000);
}
#Test (priority = 3)
public void Movies_Rating_page() throws Exception {
driver.findElement(By.xpath(".//*[#id='hotkeylnk106']/div[2]")).click();
Thread.sleep(2000);
driver.findElement(By.xpath(".//*[#id='main-
wrapper']/div/div/div[3]/div[2]/div/div[1]/div[1]/div/a/span/img")).click();
Thread.sleep(2000);
driver.findElement(By.xpath(".//*[#id='main-
wrapper']/div/div/div[2]/div[1]/ul/li[2]/span/a[2]/span[1]")).click();
Thread.sleep(3000);
driver.findElement(By.xpath(".//*
[#id='AlreadyRated']/div/div/div/section/div/a")).click();
System.out.println("Rating Page Redirection Successful");
Thread.sleep(3000);
driver.findElement(By.xpath(".//*[#id='us-jdnew-
wrapper']/div/form/div/div/div/div[2]/span[2]/span[10]")).click();
Thread.sleep(1000);
driver.findElement(By.xpath(".//*[#id='us-jdnew-
wrapper']/div/form/div/div/div/div[3]/div[3]/textarea")).sendKeys("Very nice
movie, Must watch.");
Thread.sleep(1000);
driver.findElement(By.xpath(".//*[#id='us-jdnew-
wrapper']/div/form/div/div/div/div[3]/div[4]/button[2]")).click();
Thread.sleep(3000);
System.out.println("Rating Successfully Submitted");

You can create a method and tag that method in your test method as dependsOnMethods . You can achieve it like below (i tried to answer to the best based on the info provided)
The idea here is that when your rated condition is met isMovieRated should throw exception so that Movies_Rating_page() will be skipped by testNG ,otherwise isMovieRated just returns true and nothing should be skip.
#Test
public static boolean isMovieRated(String locator) {
//check in "if" below that element has already clicked or is equal to something. I used 'AlreadyClicked' just to
give an idea as I dont have your application information.
if (driver.findElement(By.xpath(locator).getText()=="AlreadyClicked"){
throw new RuntimeException();
}
else {
return true;
}
}
Now your Movies_Rating_page() will look like this
#Test (priority = 3,dependsOnMethods = { "isMovieRated" })
public void Movies_Rating_page() throws Exception {
public static String YourLocator = "/html/body/...."
Ratings.isMovieRated(YourLocator);
..
}
here is a link for more info on testNG dependsOnMethods
Note:
The code above is not tested.
If you are doing things other than checking rating in Movies_Rating_page() then you should separate those things because everything will be skipped when an exception is thrown.
Hope this helps.

Related

How to click on an option in li tag

I am trying to do following :
Go to yelp.com
Select “Restaurants” after clcking in the drop-down box in Find
I am not able to click on "Restaurants" as xpath is not able to locate element.
I checked with selenium-webdriver, junit. Below code is working fine for me. Check this resolves for you.
#Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
driver.manage().window().maximize();
baseUrl = "http://www.yelp.com/";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void testYelpRest() throws Exception {
driver.get(baseUrl + "");
driver.findElement(By.id("find_desc")).clear();
driver.findElement(By.id("find_desc")).sendKeys("Restaurants");
driver.findElement(By.id("find_desc")).sendKeys(Keys.DOWN);
driver.findElement(By.id("find_desc")).sendKeys(Keys.ENTER);
for (int second = 0;; second++) {
if (second >= 60) fail("timeout");
try { if (isElementPresent(By.xpath("//span[#class='pagination-results-window']"))) break; } catch (Exception e) {}
Thread.sleep(1000);
}
}
#After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
you can try below code, i m sure it will work..:)
public class Yelp_dropdown {
public static void main(String[] args) {
WebDriver driver=new FirefoxDriver();
driver.get("http://www.yelp.com/");
WebDriverWait w= new WebDriverWait(driver,5);
driver.findElement(By.xpath(".//*[#id='find_desc']")).click();
w.until(ExpectedConditions.elementToBeClickable(By.xpath(".//*[#class='suggestion-detail suggestion-name' and contains (text(), 'Restaurants')]"))).click();

Selenium Parametrization

I have tried this following code to automate gmail,in the first function the browser is able to get the element till "Compose" and click on it but the next few elements like "to" , "subject" is not found ..i have specified the next elements in void mailSend() function , i am not sure why it does not read the next elements.
public class Example{
public static WebDriver driver;
#BeforeClass
public void before()
{
driver = new FirefoxDriver();
}
#Test(dataProvider = "Data-Provider-Function")
public void startup(String uName,String pass) throws Exception
{
driver.get("https://www.gmail.com");
driver.findElement(By.id("Email")).sendKeys(uName);
driver.findElement(By.id("Passwd")).sendKeys(pass);
driver.findElement(By.id("signIn")).click();
Thread.sleep(4000);
driver.findElement(By.cssSelector("div[class='T-I J-J5-Ji T-I-" +
"KE L3']")).click();
Thread.sleep(4000);
}
#DataProvider (name = "Data-Provider-Function")
public Object[][] startupProvider()
{
return new Object[][]
{
{"selva.prokarma.test#gmail.com", "prokarma"}
};
}
#Test(dataProvider="Mail Information")
public void mailSend(String to,String subject,String body) throws Exception
{
driver.navigate().refresh();
Thread.sleep(2000);
driver.findElement(By.className("vO")).sendKeys(to);
Thread.sleep(2000);
driver.findElement(By.className("aoT")).sendKeys(subject);
Thread.sleep(2000);
driver.findElement(By.cssSelector(".editable")).click();
driver.switchTo().frame(driver.findElement(By.xpath("//iframe[contains(#tabindex,'1') and contains(#frameborder,'0')]")));
driver.findElement(By.xpath("//body[#role='textbox']")).sendKeys(body);
driver.switchTo().defaultContent();
driver.findElement(By.cssSelector("div[class='T-I J-J5-Ji aoO T-I-atl L3']")).click();
Thread.sleep(4000);
driver.navigate().refresh();
Thread.sleep(4000);
}
#DataProvider (name = "Mail Information")
public Object[][] mailSendProvider()
{
return new Object[][]
{
{"selva.prokarma.test#gmail.com", "This is a Test Mail","Prokarma"},
{"selva.prokarma.test#gmail.com", "This is Test Mail 2","Hello Automation King "},
{"selva.prokarma.test#gmail.com","This is another Test Mail 3","Hello Selva"},
{"selva.prokarma.test#gmail.com","This is another Test Mail 3","Hello SelvaKumar"},
{"selva.prokarma.test#gmail.com","Hi How are you doing","Robotium Tasks to be followed"}
};
}
#AfterClass
public void tear()
{
driver.quit();
}
}
I kept the wait as 60 secs and removed all sleep statements which are not at all required. and More over i tried everything in single test method.
public class Example2 {
public static WebDriver driver;
#BeforeClass
public void before()
{
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(60000, TimeUnit.MILLISECONDS);
}
#Test(dataProvider="Mail Information")
public void mailSend(String to,String subject,String body) throws Exception
{
driver.get("https://www.gmail.com");
driver.findElement(By.id("Email")).sendKeys("xyzy#gmail.com");
driver.findElement(By.id("Passwd")).sendKeys("*********");
driver.findElement(By.id("signIn")).click();
driver.findElement(By.cssSelector("div[class='T-I J-J5-Ji T-I-KE L3']")).click();
driver.findElement(By.className("vO")).sendKeys(to);
driver.findElement(By.className("aoT")).sendKeys(subject);
driver.findElement(By.cssSelector(".editable")).click();
driver.switchTo().frame(driver.findElement(By.xpath("//iframe[contains(#tabindex,'1') and contains(#frameborder,'0')]")));
driver.findElement(By.xpath("//body[#role='textbox']")).sendKeys(body);
driver.switchTo().defaultContent();
driver.findElement(By.cssSelector("div[class='T-I J-J5-Ji aoO T-I-atl L3']")).click();
driver.navigate().refresh();
}
#DataProvider (name = "Mail Information")
public Object[][] mailSendProvider()
{
return new Object[][]
{
{"xyzy#gmail.com", "This is a Test Mail","hello"},
};
}
#AfterClass
public void tear()
{
driver.quit();
}
Attaching the output screenshot as well...

Test Automation Framework for Web Application using Java

I am beginning to write a Test Automation Framework in Java (language that I am comfortable with) for my Web Application. Currently, it is entirely tested on UI. No Backend / API testing in near sight.
I plan to use Selenium Web Driver. This framework will support both Functional/Integration and Performance testing.
I am building with Open Source Solutions for the first time (over using tools like LoadRunner) and my needs are this framework will work with Continuous Integration tools like Jenkins/Hudson and an in-house Test Management tool for reporting results.
I searched for this specific scenario but could not find one. I know there will be numerous integrations, plug-ins, etc... that needs to be built. My question is can you provide some pointers (even good reads is OK) towards beginning to build this framework with Open source solutions ?
Selenium will allow you to automate all your web (browsers) actions
automations.
Junit/TestNG as the testing framework,
including their default reports system
Maven for the project
management and lifecycle (including test phase with surefire
plugin)
Jenkins is a good integration tool that will easily
run the setup above
Good luck!
I am giving here framework functions which reduces code very much
public TestBase() throws Exception{
baseProp = new Properties();
baseProp.load(EDCPreRegistration.class.getResourceAsStream("baseproperties.properties"));
// Firefox profile creation
FirefoxProfile profile = new FirefoxProfile();
profile.setPreference("network.proxy.type", ProxyType.AUTODETECT.ordinal());
profile.setPreference("browser.cache.disk.enable", false);
profile.setPreference("network.proxy.http", "localhost");
profile.setPreference("network.proxy.http_port",8080);
driver = new FirefoxDriver(profile);
//System.setProperty("webdriver.ie.driver","E:\\Phyweb Webdriver\\IEDriverServer.exe");
//driver = new InternetExplorerDriver();
driver.manage().window().maximize();
}
//To find WebElement by id
public static WebElement FindElement(String id)
{
try
{
webElement= driver.findElement(By.id(id));
}
catch(Exception e)
{
Print(e);
}
return webElement;
}
//To find WebElement by name
public static WebElement FindElementByName(String name)
{
try
{
webElement= driver.findElement(By.name(name));
}
catch(Exception e)
{
Print(e);
}
return webElement;
}
//To find WebElement by Class
public static WebElement FindElementByClass(String classname)
{
try
{
webElement= driver.findElement(By.className(classname));
}
catch(Exception e)
{
Print(e);
}
return webElement;
}
//To get data of a cell
public static String GetCellData(XSSFSheet sheet,int row,int col)
{
String cellData = null;
try
{
cellData=PhyWebUtil.getValueFromExcel(row, col, sheet);
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return cellData;
}
//To click a button using id
public static void ClickButton(String id,String label)
{
try
{
WebElement webElement= FindElement(id);
Snooze();
webElement.click();
PrintMessage(label+" is selected");
}
catch(Exception e)
{
Print(e);
}
}
//To click a button using class
public void ClickButtonByClass(String classname,String label)
{
try
{
WebElement webElement= FindElementByClass(classname);
Snooze();
webElement.click();
PrintMessage(label+" is selected");
}
catch(Exception e)
{
Print(e);
}
}
//To enter data into Textbox
public String editTextField(int rownum, int celnum,WebElement element ,XSSFSheet sheet,String Label)
{
XSSFRow row = sheet.getRow(rownum);
XSSFCell Cell = row.getCell(celnum);
String inputValue = Cell.getStringCellValue().trim();
element.clear();//To clear contents if present
try
{
element.sendKeys(inputValue);
String elementVal=element.toString();
if(elementVal.contains("password"))
{
PrintMessage("Password is entered");
}
else
{
PrintMessage("Value entered for "+Label+" is "+inputValue);
}
}
catch(Exception e){
Print(e);
//cv.verifyTrue(false, "<font color= 'red'> Failed due to : </font> "+e.getMessage());
}
return inputValue;
}
//To enter data into Textbox
public String editTextFieldDirect(WebElement element ,String text,String label)
{
element.clear();//To clear contents if present
try
{
element.sendKeys(text);
String elementVal=element.toString();
if(elementVal.contains("password"))
{
PrintMessage("Password is entered");
}
else
{
PrintMessage("Value entered for "+label+" is "+text);
}
}
catch(Exception e){
Print(e);
//cv.verifyTrue(false, "<font color= 'red'> Failed due to : </font> "+e.getMessage());
}
return text;
}
//To select Radio button
public void ClickRadioButton(String id)
{
try
{
WebElement webElement= FindElement(id);
Snooze();
webElement.click();
text=webElement.getText();
PrintMessage(text+" is selected");
}
catch(Exception e)
{
Print(e);
}
}
//To select Link
public void ClickLink(String id,String label)
{
try
{
ClickButton(id,label);
}
catch(Exception e)
{
Print(e);
}
}
//To Click an Image button
public void ClickImage(String xpath)
{
try
{
WebElement webElement= FindElement(id);
Snooze();
webElement.click();
text=GetText(webElement);
PrintMessage(text+" is selected");
}
catch(Exception e)
{
Print(e);
}
}
//Select a checkbox
public void CheckboxSelect(String id,String label)
{
try
{
WebElement webElement= FindElement(id);
Snooze();
webElement.click();
PrintMessage("Checkbox "+label+" is selected");
}
catch(Exception e)
{
Print(e);
}
}
//To select value in Combobox
public void SelectData(String id,String label,String cellval)
{
try
{
WebElement webElement= FindElement(id);
Snooze();
webElement.click();
String elementStr=webElement.toString();
int itemIndex=elementStr.indexOf("value");
if(itemIndex>-1)
{
int endIndex=elementStr.length()-3;
String item=elementStr.substring(itemIndex+7, endIndex);
if(cellval=="0")
{
PrintMessage(item+" is selected for "+label);
}
else
{
PrintMessage(cellval+" "+label+" is selected");
}
}
else
{
PrintMessage(cellval+" is selected for "+label);
}
}
catch(Exception e)
{
Print(e);
}
}
//To check if WebElement with id exists
public static boolean isExists(String id)
{
boolean exists = false;
driver.manage().timeouts().implicitlyWait(0, TimeUnit.MILLISECONDS);
try
{
exists=driver.findElements( By.id(id) ).size() != 0;
}
catch (Exception e)
{
Print(e);
}
if(exists==true)
return true;
else
return false;
}
//To check if WebElement with name exists
public static boolean isExistsName(String name)
{
boolean exists = false;
driver.manage().timeouts().implicitlyWait(0, TimeUnit.MILLISECONDS);
try
{
exists=driver.findElements( By.name(name) ).size() != 0;
}
catch (Exception e)
{
if(e.getMessage().contains("InvalidSelectorError"))
{
System.out.println("");
}
else
Print(e);
}
if(exists==true)
return true;
else
return false;
}
//Explicit wait until a element is visible and enabled using id
public void ExplicitlyWait(String id)
{
try
{
WebElement myDynamicElement = (new WebDriverWait(driver, 10))
.until(ExpectedConditions.presenceOfElementLocated(By.id(id)));
}
catch(Exception e)
{
Print(e);
}
}
//Explicit wait until a element is visible and enabled using classname
public void ExplicitlyWaitByClass(String classname)
{
try
{
WebElement myDynamicElement = (new WebDriverWait(driver, 10))
.until(ExpectedConditions.presenceOfElementLocated(By.className(classname)));
}
catch(Exception e)
{
Print(e);
}
}
//Explicit wait until a element is visible and enabled using id
public void ExplicitlyWaitSpecific(int sec,String id)
{
try
{
WebElement myDynamicElement = (new WebDriverWait(driver, sec))
.until(ExpectedConditions.presenceOfElementLocated(By.id(id)));
}
catch(Exception e)
{
Print(e);
}
}
//Snooze for 10 seconds
public static void Snooze()
{
try
{
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
catch(Exception e)
{
Print(e);
}
}
//Snooze for Secs
public static void SnoozeSpecific(int seconds)
{
try
{
driver.manage().timeouts().implicitlyWait(seconds, TimeUnit.SECONDS);
}
catch(Exception e)
{
Print(e);
}
}
//Sleep for milliSeconds
public static void Sleep(int milisec) throws InterruptedException
{
Thread.sleep(milisec);
}
//To get text using text()
public static String GetText(WebElement element)
{
try
{
text=element.getText();
}
catch(Exception e){
Print(e);
}
return text;
}
//To get text using getAttribute("value")
public static String GetTextAttribute(WebElement element)
{
try
{
text=element.getAttribute("value");
}
catch(Exception e){
Print(e);
}
return text;
}
//To Print error messages to both Console and Results file
public static void Print(Exception e)
{
Reporter.log("Exception is :"+e.getMessage());
System.out.println(e);
}
//To Print messages to both Console and Results file
public static void PrintMessage(String str)
{
Reporter.log(str);
System.out.println(str);
}
//To Print Blank row
public static void BlankRow()
{
Reporter.log(" ");
System.out.println(" ");
}
//To Print Sub header
public static void Header(String str)
{
BlankRow();
Reporter.log("***********************"+str+" Verifications***********************");
System.out.println("***********************"+str+" Verifications***********************");
BlankRow();
}
//To Print Sub header
public static void SubHeader(String str)
{
BlankRow();
Reporter.log("-----------------------"+str+" Verifications-----------------------");
System.out.println("-----------------------"+str+" Verifications-----------------------");
BlankRow();
}
So long as you have a command line for kicking off your framework and you report back using the xunit log format then you should be good for integration with any number of Continuous integration frameworks.
Your trade off on running a browser instance under load will be fewer virtual users per host and a very careful examination of your load generator resources under load. Don't forget to include monitoring API in your framework for system metrics under load and an auto evaluation engine related to SLA metrics acceptance to determine pass of fail criteria under load at a given load point.
We are begining to develop something very related to your needs; Java, Webdriver, Jenkins, Maven, etc. We are quite new to automation here, but still have good Java ressources.
We are builing our framework based on Tarun Kumar from www.seleniumtests.com.
He's got a lot of good videos from Youtube (sounds quality is not so good), and he manage to create something very user friendly, using PageObjects Pattern.
If you don't have any clue where to start, I would start from there.
Good luck!
I created a java library on the top of selenium which simplifies test automation of a website. It has an implicit waiting mechanism and is easy to use:
https://github.com/gartenkralle/web-ui-automation
Example:
import org.junit.Test;
import org.openqa.selenium.By;
import common.UserInterface;
import common.TestBase;
public class Google extends TestBase
{
private final static String GOOGLE_URL = "https://www.google.com/";
private final static By SEARCH_FIELD = By.xpath("//input[#id='lst-ib']");
private final static By AUTO_COMPLETION_LIST_BOX = By.xpath("//*[#id='sbtc']/div[2][not(contains(#style,'none'))]");
private final static By SEARCH_BUTTON = By.xpath("//input[#name='btnK']");
#Test
public void weatherSearch()
{
UserInterface.Action.visitUrl(GOOGLE_URL);
UserInterface.Action.fillField(SEARCH_FIELD, "weather");
UserInterface.Verify.appeared(AUTO_COMPLETION_LIST_BOX);
UserInterface.Action.pressEscape();
UserInterface.Action.clickElement(SEARCH_BUTTON);
}
}
Selenium WebDriver is surely a tool for UI automation and we use it extensively to do cross Browser testing on Cloud Solutions like Browser Stack.
Our use case let us build an open source Framework "omelet" built in Java using TestNG as test runner , which takes care of almost everything related to web-testing and leaves us to actually automated application rather than thinking about reports , parallel run and CI integration etc.
Suggestion, Contribution always welcome :)
Documentation over here and
Github link over here
Do remember to checkout 5 min tutorial on website
For Functional Regression test:
Selenium Webdriver - Selenium a Web based automation tool that automates anything and everything available on a Web page. you use Selenium Webdriver with JAVA.
Watij- Web Application Testing in Java
Automates functional testing of web applications through real web browsers.
TestProject - It supports for testing both web and Mobile (Android & iOS).
For Non-functional test:
Gatling- For performance testing and Stress testing
Apache JMeter - For Volume, Performance, Load & Stress testing
CI tool:
Jenkins- Jenkins provides continuous integration services for software development.
For Functional Regression test:
TestProject
Selenium
Cucumber : It's a BDD tool
For Non-functional: Performance and Load testing:
JMeter
Note: TestComplete is a very good commercial tool.

org.openqa.selenium.InvalidElementStateException: Element is read-only and so may not be used for actions

n my page there are lots of drop down boxes and text fields.while testing the page in eclipse IDE its showing the above exception. I am not able to find any solution for this Exception
This is my code:
public class QuoteNewEntry {
private WebDriver driver;
private String baseUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
#Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = "http:///";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void testQuoteNewEntry() throws Exception {
driver.get(baseUrl + "");
System.out.println("The current Url: "+ driver.getCurrentUrl());
assertEquals("", driver.getTitle());
driver.findElement(By.id("RdbtnLight")).click();
driver.findElement(By.id("txtUserName")).clear();
driver.findElement(By.id("txtUserName")).sendKeys("tom");
driver.findElement(By.id("txtpassword")).clear();
driver.findElement(By.id("txtpassword")).sendKeys("tom");
driver.findElement(By.id("btnSubmit")).click();
assertEquals("", driver.getTitle());
driver.findElement(By.id("btnTrade")).click();
System.out.println("The current Url: "+ driver.getCurrentUrl());
assertEquals("", driver.getTitle());
driver.findElement(By.id("btnQuote")).click();
System.out.println("The current Url: "+ driver.getCurrentUrl());
assertEquals("Quote", driver.getTitle());
driver.findElement(By.id("ContentPlaceHolder1_btnNew")).click();
System.out.println("The current Url: "+ driver.getCurrentUrl());
new Select(driver.findElement(By.id("ContentPlaceHolder1_ddlLineOfBus"))).selectByVisibleText("FCL");
driver.findElement(By.id("ContentPlaceHolder1_txtCaptured")).clear();
driver.findElement(By.id("ContentPlaceHolder1_txtCaptured")).sendKeys("3");
driver.findElement(By.id("ContentPlaceHolder1_rbtn3rdParty")).click();
Thread.sleep(5000);
driver.findElement(By.id("ContentPlaceHolder1_txtTotalTransitDays")).clear();
driver.findElement(By.id("ContentPlaceHolder1_txtTotalTransitDays")).sendKeys("10");
driver.findElement(By.id("ContentPlaceHolder1_txtVoyageFrequency")).clear();
driver.findElement(By.id("ContentPlaceHolder1_txtVoyageFrequency")).sendKeys("weekly");
Thread.sleep(5000);
driver.findElement(By.id("ContentPlaceHolder1_txtExternal")).clear();
driver.findElement(By.id("ContentPlaceHolder1_txtExternal")).sendKeys("ex");
Thread.sleep(5000);
driver.findElement(By.id("ContentPlaceHolder1_btnSave")).click();
try{
driver.findElement(By.xpath("//input[#value = 'alert']")).click();
Thread.sleep(5000);
}
catch(WebDriverException we){
}
}
#After
public void tearDown() throws Exception {
//driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
private String closeAlertAndGetItsText() {
try {
Alert alert = driver.switchTo().alert();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alert.getText();
} finally {
acceptNextAlert = true;
}
}
}
The exception suggests your are trying to perform an edit action on an element that is read-only. This includes actions such as SendKeys() and Click(). You can either make these elements writable in your application, or you must check if they are read-only prior to accessing them; if they are you cannot perform the action.

catching unknown host exception in codename one

I am building an app using codename one
So the thing is, I need to access a URL using the app. THe URL brings back some result which I show on the screen.
SO I use these lines to do that :
ConnectionRequest c = new ConnectionRequest() {
protected void readResponse(InputStream input) throws IOException {
ByteArrayOutputStream bs = new ByteArrayOutputStream();
int ch;
while ((ch = input.read()) != -1) {
bs.write(ch);
}
serverOutput = new String(bs.toByteArray());
bs.close();
}
};
c.setUrl("My URL HERE");
c.setPost(false);
NetworkManager.getInstance().addToQueueAndWait(c);
So, now , if the gprs is active, this code works fine.
BUT , if the GPRS is inactive, it throws an Unknow Host Exception
SO to catch this error, i TRIED to use a try catch block like this:
try{
NetworkManager.getInstance().addToQueueAndWait(c);
}
catch(Exception e)
{
Sys.out.pln(e.troString());
}
But, i still get the error in the form of a dialog in the app. How do i catch this error and put my own handling for it?
UPDATE 1:
Am not sure this is necessarily a codename one specific questions, or related to java ...so just help me out with this.
Try this to handle generic errors for all connections:
NetworkManager.getInstance().addErrorListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
//handle your error here consume the event
evt.consume();
}
});
Or override:
protected void handleErrorResponseCode(int code, String message) {
}
And:
protected void handleException(Exception err) {
}
In your connection request code to do this for just one class.
Try it...
public void init(Object context) {
Display.getInstance().addEdtErrorHandler(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
evt.consume();
Throwable exception = (Throwable) evt.getSource();
}
});
}

Resources