Hey guys I am trying to customize the output of my selenium framework using testNG. Right now I have an 'action' class which is wrapping all the selenium methods and I am wraping those up in try catches. Here's an example. (I am manually throwing the exception for testing purposes.)
public void closeBrowser(){
try{
driver.quit();
throw new WebDriverException();
}
catch(Exception e){
ExceptionHandler exception = new ExceptionHandler(e, null);
}
}
My exception handler class looks like this:
public ExceptionHandler(Exception exceptionName, String element){
this.exceptionName = exceptionName;
this.element = element;
report();
}
public void report(){
String delims = "[.]";
String[] tokens = exceptionName.getClass().toString().split(delims);
System.out.println(tokens[tokens.length-1]);
switch(tokens[tokens.length-1]){
case "WebDriverException":
System.out.println("Made it to case 1");
Reporter.log("Test Message here <------ \n", true);
break;
default:
Reporter.log("Unknown Exception");
}
}
When I run I get this output on the console:
WebDriverException
Made it to case 1
Test Message here <------
But I never get anything in the HTML files that TestNG generates. Any ideas??
Related
Am working on selenium Automation
I want to know the name of which elements is not found when test cases got failed instead of getting object not found with property By.id("Login")
am expecting output like Object not found LoginButton(Customized name which i will give in code) when test cases fails due to defect
public static void logonCustomerPortal() throws Exception{
Thread.sleep(5000);
driver.findElement(By.xpath("//a[#id='nav_login']/span")).click();
Thread.sleep(2000);
}
I am new to Automation. Can anyone please help me ?
try to use try catch like this :
public void urmethod(){
try {
//do your code
}catch (Exception e){
e.printStackTrace();
}
}
this will print details of your error, in other words, what kind of error, in which line it fails...etc
Hello i really need help with Selenium WebDriver using TestNG and Excel
i try to get data from excel to open browser and navigate URL. its work successfully and terminal and testng report showing test pass but its not open browser or doing anything its just run its self and show report
Config File
public void openBrowser(String browser){
try {
if (browser.equals("Mozilla")) {
driver = new FirefoxDriver();
} else if(browser.equals("IE")){
driver = new InternetExplorerDriver();
} else if(browser.equals("Chrome")){
System.setProperty("webdriver.chrome.driver", "\\Applications\\Google Chrome.app\\Contents\\MacOS\\Google Chrome ");
driver = new ChromeDriver();
}
} catch (Exception e) {
}
}
public void navigate(String baseUrl){
try {
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
driver.navigate().to(baseUrl);
} catch (Exception e) {
}
}
And Test Execute File
public class NewTest {
public String exPath = Config.filePath;
public String exName = Config.fileName;
public String exWrSheet = "Logiin Functional Test";
public Config config;
#BeforeTest
public void openBrowser() {
config = new Config();
Excel.setExcelFile(exPath+exName, exWrSheet);
String browser = Excel.getCellData(1, 2);
config.openBrowser(browser);
}
#BeforeMethod
public void navigate() {
config = new Config();
Excel.setExcelFile(exPath+exName, exWrSheet);
String baseUrl = Excel.getCellData(2, 2);
config.navigate(baseUrl);
}
#Test
public void test() {
System.out.println("Test");
}
#AfterTest
public void closeBroser() {
//Config.tearDown();
}
I don't have quite enough rep to make a comment, which I would prefer here, but if you aren't getting any sort of exception, I'd suspect the value you're getting for the browser variable is not matching anything in your if-then-else in openBrowser and then falling through. Step through the code with a debugger or just add:
String browser = Excel.getCellData(1, 2);
System.out.println("Browser value from Excel =" + browser);
config.openBrowser(browser);
to see what you're reading from the file.
1 - TestNg is always pass because you are using "void" method and you catch "all" exception
2 - No browser opened because in openBrowser(String browser), NullPointException throws and you already catch it.
-> you need to init an instance of WebDriver and pass it through your test.
My end goal is to confirm that I have Java, Selenium WebDriver, and JUnit functioning such that I can run an automated test case utilizing these technologies.
What I have done so far:
installed Selenium IDE (v 2.8.0) for Firefox (v 34.0.5)
recorded a simple test case using Selenium IDE and added the test case to a test suite
in Selenium IDE exported the test case using the option: File->Export Test Case As...->Java / JUnit 4 / WebDriver
downloaded and installed JUnit 4 from: https://github.com/junit-team/junit/wiki/Download-and-Install (Plain-old jar method)
downloaded and installed Selenium client and WebDriver Java language binding (v 2.44.0) from: http://www.seleniumhq.org/download/
performed some slight modifications to the code generated in step 3 such as removing the package statement at the beginning
compiled the code with the following command (windows command prompt):
C:\docs\tech\code\myCode\java\testing\selenium\utest\practice>C:\java\jdk\bin\javac.exe -cp C:\docs\installs\programming\automation\test\xUnit\java\jUnit\junit\v4_12\junit-4.12.jar;C:\docs\installs\programming\automation\test\xUnit\java\jUnit\hamcrest\hamcrest-core-1.3.jar;C:\docs\installs\programming\automation\web\selenuim\webdriver\java\selenium-2.44.0\selenium-java-2.44.0.jar C:\docs\tech\code\myCode\java\testing\selenium\utest\practice\TestGooglePlayApp.java
this compiles with no warnings/errors
attempt to execute the code with the following command:
C:\docs\tech\code\myCode\java\testing\selenium\utest\practice>java -cp .;C:\docs\installs\programming\automation\test\xUnit\java\jUnit\junit\v4_12\junit-4.12.jar;C:\docs\installs\programming\automation\test\xUnit\java\jUnit\hamcrest\hamcrest-core-1.3.jar;C:\docs\installs\programming\automation\web\selenuim\webdriver\java\selenium-2.44.0\selenium-java-2.44.0.jar TestGooglePlayApp
Actual Result:
The output of this attempt is:
Exception in thread "main" java.lang.NoSuchMethodError: main
No other error/warning is given and no indication is given that the code begins to execute
Expected Result:
This is my first time interacting with these technologies so I'm learning as I go! However, based on the research I have done my expectation is that a local Selenium WebDriver instance will be initialized as a Firefox Driver. This Firefox Driver will be sent instructions by the Java code in order to carry out the steps in the test case. JUnit will then indicate somehow on the command line the Pass/Fail status of the test case.
The big assumption I have here is that the Selenium Server/Selenium RC is not required in this case since all I intend to do is execute a local Selenium WebDriver script. Furthermore, my hope is that this can be launched directly from the command-line independent of Eclipse, Maven, etc. I would like to be able to send the final Java class to a colleague and the only dependency for expected execution would be a working SDK of Java on the end machine.
What's Next?
I'm looking for advice on what I can do to get this code up and running under the restraints I have outlined. It may be that the code needs to be modified. It may be that my expectations need to be tempered down and it's just not possible to do everything I want directly from the command-line. It may be that I did not compile the code correctly or some library is missing. It may be that... okay you get the point!
Other Relevant Details:
OS = Windows 7 - 64 bit
Here is the contents of TestGoogleApp.java:
import java.util.regex.Pattern;
import java.util.concurrent.TimeUnit;
import org.junit.*;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
public class TestGooglePlayApp {
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 = "https://www.google.com/";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void test000() throws Exception {
driver.get("http://www.google.com/");
// COMMENT: Assert the 'Apps' icon is present and then click on it
assertTrue(isElementPresent(By.cssSelector("a.gb_C.gb_Sa")));
driver.findElement(By.cssSelector("a.gb_C.gb_Sa")).click();
// COMMENT: Assert the 'Play' app is present and then click on the 'Play' app and wait for the expected contents to load
assertTrue(isElementPresent(By.cssSelector("#gb78 > span.gb_s")));
driver.findElement(By.cssSelector("#gb78 > span.gb_s")).click();
// COMMENT: Assert that the input element associated with search queries is present and then type 'Testing' in the input element associated with search queries
assertTrue(isElementPresent(By.id("gbqfq")));
driver.findElement(By.id("gbqfq")).clear();
driver.findElement(By.id("gbqfq")).sendKeys("Testing");
// COMMENT: Click on the 'Search' element to perform a query for the input query term previously entered and wait for the expected contents to load
driver.findElement(By.id("gbqfb")).click();
// COMMENT: Assert that the desired result is contained in the search results returned and then click on the desired search result and wait for the expected contents to load
for (int second = 0;; second++) {
if (second >= 60) fail("timeout");
try { if (isElementPresent(By.linkText("Software Testing Concepts"))) break; } catch (Exception e) {}
Thread.sleep(1000);
}
driver.findElement(By.linkText("Software Testing Concepts")).click();
for (int second = 0;; second++) {
if (second >= 60) fail("timeout");
try { if ("Software Testing Concepts - Android Apps on Google Play".equals(driver.getTitle())) break; } catch (Exception e) {}
Thread.sleep(1000);
}
// COMMENT: Assert that the page contains the expected content as follows: 1) title of app 2) user rating 3) number of users who have rated the app 4) format of text value of user rating (4.0) 5) format of text value for number of user who have rated the app (128)
for (int second = 0;; second++) {
if (second >= 60) fail("timeout");
try { if (isElementPresent(By.cssSelector("div.score"))) break; } catch (Exception e) {}
Thread.sleep(1000);
}
for (int second = 0;; second++) {
if (second >= 60) fail("timeout");
try { if (isElementPresent(By.cssSelector("span.reviews-num"))) break; } catch (Exception e) {}
Thread.sleep(1000);
}
try {
assertTrue(Pattern.compile("[0-9]\\.[0-9]").matcher(driver.findElement(By.cssSelector("div.score")).getText()).find());
} catch (Error e) {
verificationErrors.append(e.toString());
}
try {
assertTrue(Pattern.compile("[0-9]+").matcher(driver.findElement(By.cssSelector("span.reviews-num")).getText()).find());
} catch (Error e) {
verificationErrors.append(e.toString());
}
// COMMENT: store value for user rating and store value for number of users who have rated the app
String _currentUserRating = driver.findElement(By.cssSelector("div.score")).getText();
System.out.println(_currentUserRating);
String _numOfUserRatings = driver.findElement(By.cssSelector("span.reviews-num")).getText();
System.out.println(_numOfUserRatings + "HELLO");
}
#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 boolean isAlertPresent() {
try {
driver.switchTo().alert();
return true;
} catch (NoAlertPresentException e) {
return false;
}
}
private String closeAlertAndGetItsText() {
try {
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alertText;
} finally {
acceptNextAlert = true;
}
}
}
I've written a standalone function for my selenium script so that when I want to interact with an object I first check if it exists, to do this I've already specified things such the method to identify it by and the data to use etc, and have some methods like so: -
public WebElement waitforElement(individualThreadSession threadSesh) {
String IDString = threadSesh.objLocVal; //This will be the string value to use to identify
String IDType = threadSesh.objLocType; //This will be something like "CSS"/"XPATH" etc
WebElement returnedElement = null;
for (int second = 0; second < threadSesh.sessionWait; second++) {
Action tempAction = new Action();
tempAction.simpleWait(1);
try {
if(IDType.toString().equals("CSS")){
if(isElementPresent(By.cssSelector(IDString), threadSesh)){
returnedElement = threadSesh.driver.findElement(By.cssSelector(IDString));
break;
}
}
else if(IDType.toString().equals("XPATH")){
if(isElementPresent(By.xpath(IDString), threadSesh)) {
returnedElement = threadSesh.driver.findElement(By.xpath(IDString));
break;
}
}
else if(IDType.toString().equals("ID")){
if(isElementPresent(By.id(IDString), threadSesh)) {
returnedElement = threadSesh.driver.findElement(By.id(IDString));
break;
}
}
else if(IDType.toString().equals("NAME")){
if(isElementPresent(By.name(IDString), threadSesh)){
returnedElement = threadSesh.driver.findElement(By.name(IDString));
break;
}
}
else if(IDType.toString().equals("PARTIALLINKTEXT")){
if(isElementPresent(By.partialLinkText(IDString), threadSesh)) {
returnedElement = threadSesh.driver.findElement(By.partialLinkText(IDString));
break;
}
}
else if(IDType.toString().equals("LINKTEXT")){
if(isElementPresent(By.linkText(IDString), threadSesh)) {
returnedElement = threadSesh.driver.findElement(By.linkText(IDString));
break;
}
}
} catch (Exception e) {System.out.println("When trying to find the obj error encountered - " + e);}
}
return (returnedElement);
}
and this: -
public boolean isElementPresent(By myObject, individualThreadSession threadSesh) {
try{
System.out.println("actually check!");
if (threadSesh.driver.findElement(myObject).isEnabled() && threadSesh.driver.findElement(myObject).isDisplayed()) {
return true;
} else {
return false;
}
} catch (NoSuchElementException e){
return(false);
}
}
But every time I run this it errors with the below and exits the test: -
Test failed with the following error: - org.openqa.selenium.NoSuchElementException:
Unable to find element with xpath == .//*[#id='main']/div[1]/div[1]/h1/span
Shouldn't this work?
I think it could be because I also have an WebDriverEventListener running which I'm guessing is catching this error and exiting the test etc, is there any way I can stop this eventlistener from listening during this waitforelement process?
If not is there a way I can check if the object is enable and visible or not without it throwing an exception?
The event listener is like so: -
WebDriverEventListener listener = new AbstractWebDriverEventListener() {
#Override
public void onException(Throwable t, WebDriver driver) {
//Add in take screenshot here at some stage!
if(!errorsCaught){
errorsCaught=true;
try{
driver.quit();
}catch(WebDriverException theError){}
System.out.println();
System.out.println(Thread.currentThread().getName() + " has encountered an error ");
individualThreadSession.this.endSession(individualThreadSession.this, t);
}
}
};
More digging reveals that it looks like it is the listener picking up things before the catch does anything with it, so now I need to somehow work out how to get it to ignore the error! Any ideas?
I had failed to spot one key line in my event listener, the #Override! This was causing my listener to pick up all exceptions before any catch's I may have also put in, and my listener will just kill off the session and close the run as it should (even though I don't want it to do something in that case).
To get round this issue as I always go through the same route above to check for an object before interacting with it I can be fairly confident that this object will always be there before trying anything or timeout and exit gracefully.
So I've inserted a basic check like so: -
t.getClass().getSimpleName().toLowerCase().equals("nosuchelementexception")
So if the error is a nosuchelementexception I don't bother doing anything with it and just go back into my loop, simples! :)
If findEelement is unable to find the element you will get a NoSuchElementException. This is expected. Instead, try to use findElements that will return an empty list instead of an exception if no elements are present.
Two ways of solving your problem:
Boolean isPresent = driver.findElements(myObject).size()<0
or
private boolean doesElementExist (myObject) {
try {
driver.findElement(myObject);
} catch (NoSuchElementException e) {
return false;
}
return true;}
I use Selenium Web Driver in Eclipse with JUnit. I need create simple checking if some text exists on the page - if it is, than I need generate error. I want this error to be displayed in JUnit failure trace. This is my code:
public class Check {
#Rule
public ErrorCollector errCollector = new ErrorCollector();
#FindBy(tagName="body")
#CacheLookup
private WebElement titl;
#FindBy(partialLinkText="Exception")
#CacheLookup
private WebElement excep;
public void check_false(String t, String r) {
try {
String bodyText = titl.getText();
Assert.assertFalse("Exception found", bodyText.contains(t)); }
catch (AssertionError e) {
System.err.println(r + ": " + e.getMessage());
System.out.println(excep.getText());
errCollector.addError(e);
}
}
If I get error, it is displayed in Eclipse consol, but test if shown as without error in JUnit and no exception message is displayed. How can I make checking properly?
I use
AssertJUnit.assertFalse("Exception found", bodyText.contains(t));
It's from http://testng.org/doc/index.html
see http://testng.org/javadoc/org/testng/AssertJUnit.html
Within eclipse when my test fails, in the junit window I get the stackstrace. Have never tried collecting the errors. It would throw an
AssertionFailedError
if the test fails but if you catch it, I don't know if the stacktrace will be in the JUnit window.
This might not be quite what you're after, in which case ignore it, but you can simply fail it and supply an optional message as to why.
public void checkText(String actual, String expected){
try{
if(!expected.equals(actuals){
fail("Expected : [ " expected + " ] , actual [" + actual + "]"
}catch(SomeOtherException soe){
fail(soe.getMessage());
}
}