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.
Related
#BeforeMethod
public void setup ()
{
System.setProperty("webdriver.chrome.driver", "src\\test\\resources\\chromedriver.exe");
driver = new ChromeDriver(); // Opens Chrome browser
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS);
//driver.manage().window().maximize();
}
#AfterMethod
public void tearDown() throws Exception
{
Thread.sleep(5*1000);
driver.quit();
}
#Test
public void browserCommandsTests()
{
try {
driver.get("http://www.costco.com");
Thread.sleep(3 * 1000);
driver.navigate().to("http://www.facebook.com");
Thread.sleep(3 * 1000);
driver.navigate().back();
Thread.sleep(3 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
When i'm testing this code after opening the urls it doesn't closes the
testing browser.
it opens only 1 link and closes browser when i'm getting only 1 url. but as soon as i try to get 2nd url it opens 2nd url and after it doesn't closes the browser under test.
It is your tag #AfterMethod change it to AfterClass (also you can try close instead of quit):
#AfterClass
public void tearDown() throws Exception
{
driver.close();
}
Also, friendly advice, using the thread.sleep will cause you more grief than joy. The alternative is to use driver.findElement() in a try/catch and depending on the result (true/false) direct your flow from there.
Best of luck!
#AfterMethod
public void tearDown() throws Exception
{
driver.quit();
}
My JUnit Tests run fine in eclipse and pass locally however in Jenkins my 1st test passes and 2nd one fails and I know why but cant figure out the solution. The Jenkins output says it cant find the element however it is there and I have the proper waits.
Here is the 1st test case that passes.
#Before
public void setUp() throws Exception {
System.setProperty("webdriver.chrome.driver", "C:\\eclipse\\chromedriver\\chromedriver.exe");
driver = new ChromeDriver();
homeUrl = "https://myadp.adpcorp.com/wps/myportal/main/myADP_new";
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.get(homeUrl);
}
//Full test
#Test
public void fullTest() throws Exception {
step01_VerifyHomePage();
}
// Go to Home page and verify title
public void step01_VerifyHomePage() throws Exception {
driver.getTitle().contains(homeTitle);
Thread.sleep(3000);
}
#After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
This is the one that fails in Jenkins
//Full test
#Test
public void fullTest() throws Exception {
step02_HoverMyWorkSpace();
}
public void step02_HoverMyWorkSpace() throws Exception {
WebDriverWait wait = new WebDriverWait(driver,20000);
wait.until(ExpectedConditions.visibilityOfElementLocated((By.id("DivMyWorkList"))));
if ( driver.findElement(By.id("DivMyWorkList")).isDisplayed()){
System.out.println("DivMyWorkList Visiable");
}else{
System.out.println("DivMyWorkList NOT Visiable");
}
// Assert.assertEquals(true, workspace.isDisplayed());
// Thread.sleep(3000);
}
#After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
Jenkins Output
The problem i think is that Jenkins cant find the element because the page is not coming up in what ever environment it is using. When I use
wait.until(ExpectedConditions.visibilityOfElementLocated((By.id("DivMyWorkList")))); Jenkins test hangs and times out.
If this is the case is there a way around this? It dose not make sense that the 1st test passes by using the same url and the 2nd one uses same url to the exact same page and it can find the title but not the web element.
I am using a VM and created a free style project on it.
I have been working on this for the past week any help would be appreciated.
Below is my SAMPLE code in which i am trying to create a simple report using the Leanft in which i am getting on result xml file.
#Test
public void Google() throws Exception {
Reporter.init();
WebDriver driver = new FirefoxDriver();
driver.get("https://www.google.com");
Thread.sleep(4000);
if( driver.getTitle().equalsIgnoreCase("google")){
Reporter.reportEvent("test", "test",Status.Failed);
}
Reporter.generateReport();
driver.quit();
}
As specified in the docs, if you're going to use a custom framework you'll also need to initialize the SDK (SDK.init() and SDK.cleanup())
E.G.
public static void main(String [] args){
// initialize the SDK and report only once per process
try{
ModifiableSDKConfiguration config = new ModifiableSDKConfiguration();
config.setServerAddress(new URI("ws://myServerAddress:5095"));
SDK.init(config);
Reporter.init();
//put your test code here.
//Generate the report and cleanup the SDK usage.
Reporter.generateReport();
SDK.cleanup();
} catch(Exception e){
}
}
I see nothing wrong with your code as the report generates as you told it too.
However, I believe you were wanting something more like this to show that it PASSES when it finds the Google title:
#Test
public void Google() throws Exception {
Reporter.init();
WebDriver driver = new FirefoxDriver();
driver.get("https://www.google.com");
Thread.sleep(4000);
if( driver.getTitle().equalsIgnoreCase("google")){
Reporter.reportEvent("test", "test",Status.Passed);
} else {
Reporter.reportEvent("test","test",Status.Failed);
}
Reporter.generateReport();
driver.quit();
}
This may be as simple as getting a variable from another class. I am still learning Java and Selenium.
I would like the test run report (ExtentReports) to be able to report the browser at a #Test level (capabilities). Currently Grid runs the same tests on different browsers, and the report does not distinguish them.
Using Selenium Grid, I define my #Test's Capabilities (including browser) with #BeforeMethod. I do this in my BaseTest class.
public class BaseTest {
#BeforeMethod(alwaysRun = true)
#Parameters({ "platform", "browser", "version" })
public void setup(String platform, String browser, String version)
throws MalformedURLException, InterruptedException {
RemoteWebDriver driver = null;
//important: Thread local!
threadedDriver = new ThreadLocal<RemoteWebDriver>();
DesiredCapabilities caps = new DesiredCapabilities();
// Platforms
if (platform.equalsIgnoreCase("windows"))
caps.setPlatform(Platform.WINDOWS);
if (platform.equalsIgnoreCase("XP"))
caps.setPlatform(Platform.XP);
if (platform.equalsIgnoreCase("WIN8"))
caps.setPlatform(Platform.WIN8);
if (platform.equalsIgnoreCase("WIN8_1"))
caps.setPlatform(Platform.WIN8_1);
if (platform.equalsIgnoreCase("ANY"))
caps.setPlatform(Platform.ANY);
if (platform.equalsIgnoreCase("MAC"))
caps.setPlatform(Platform.MAC);
if (platform.equalsIgnoreCase("Android"))
caps.setPlatform(Platform.ANDROID);
// Browsers
if (browser.equalsIgnoreCase("Internet Explorer"))
caps.setBrowserName("internet explorer");
if (browser.equalsIgnoreCase("Firefox"))
caps.setBrowserName("firefox");
if (browser.equalsIgnoreCase("chrome"))
caps.setBrowserName("chrome");
if (browser.equalsIgnoreCase("MicrosoftEdge"))
caps.setBrowserName("MicrosoftEdge");
if (browser.equalsIgnoreCase("iPad"))
caps.setBrowserName("ipad");
if (browser.equalsIgnoreCase("iPhone"))
caps.setBrowserName("iphone");
if (browser.equalsIgnoreCase("Android"))
caps.setBrowserName("android");
// Version
caps.setVersion(version);
System.out.println(caps);
System.out.println(browser);
//Initialize driver with capabilities
driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), caps);
//this uses below methods to set above RemoteWebDriver to the getDriver()
//method in a threaded instance.
setWebDriver(driver);
initialize();
}
}
So now I have a browser variable local to each threaded Grid test run. I need to get that variable into each #Test method. Here is my #Test in a separate class. At the beginning of the try statement I would like to print the browser variable for the current threaded Grid test capabilities
public class Workflow1 extends BaseTest {
#Test
public void Workflow1TestInvalidPolicyNumbers() throws InterruptedException {
HomePage homePage = new HomePage(getDriver());
ExtentTest testReporter = ComplexReportFactory.getTest();
try {
System.out.println("This is the browser:" + ??(help here)??);
loginMethod("TestUser","TestPassword");
homePage.setFindAPersonOrPolicySearchField("1234");
homePage.clickSearchButton();
testReporter.log(LogStatus.INFO, "Searched \"1234\"");
Thread.sleep(2000);
if (getDriver().getPageSource().contains("Policy numbers should be 7 or 10 digits long"))
testReporter.log(LogStatus.PASS, "Policy numbers should be 7 or 10 digits long");
else
testReporter.log(LogStatus.FAIL, "Results incorrect" + testReporter.addScreenCapture(ComplexReportFactory.CaptureScreen(getDriver())));
} catch (Exception e) {
testReporter.log(LogStatus.ERROR, "Exception found: " + e.getMessage()
+ testReporter.addScreenCapture(ComplexReportFactory.CaptureScreen(getDriver())));
System.out.println(e);
}
}
It looks like the browser information is passed into the BaseTest.java class in the setup() method.
You could store this data in a variable which would then be available to all dependant classes:
public class BaseTest {
protected String browser; // add a property to hold this value
#BeforeMethod(alwaysRun = true)
#Parameters({ "platform", "browser", "version" })
public void setup(String platform, String browser, String version)
throws MalformedURLException, InterruptedException {
this.browser = browser; // store the given browser string
RemoteWebDriver driver = null;
//important: Thread local!
threadedDriver = new ThreadLocal<RemoteWebDriver>();
DesiredCapabilities caps = new DesiredCapabilities();
// Platforms
if (platform.equalsIgnoreCase("windows"))
caps.setPlatform(Platform.WINDOWS);
And then the BaseTest subclasses could reference it directly:
public class Workflow1 extends BaseTest {
#Test
public void Workflow1TestInvalidPolicyNumbers() throws InterruptedException {
HomePage homePage = new HomePage(getDriver());
ExtentTest testReporter = ComplexReportFactory.getTest();
try {
System.out.println("This is the browser:" + browser); // then retrieve it
You can also get the browser flavor name and a whole bunch of information by querying the RemoteWebDriver object itself to reveal the actual capabilities by invoking
getDriver().getCapabilities().getBrowserName()
This does away with the need to even have the browser flavor as a separate data member in the test class.
See here for javadocs.
I'm automating a php web page using webdriver and java language. My code was executing and I was able to perform actions on web page, but today only the login method is executing and my second method gets failed everytime I run. I'm so worried why it is happening. Please help, I'm new in automation testing.
public class TestNGClass {
private String baseUrl = "http://test.com/test2/1.4.6.3/public/admin/";
private WebDriver driver = new FirefoxDriver();
#Test
public void login() {
driver.manage().window().maximize();
driver.get(baseUrl);
driver.findElement(By.name("username")).sendKeys("abc");
driver.findElement(By.name("password")).sendKeys("123");
driver.findElement(By.name("login")).submit();
System.out.print("\nCongrats..You have successfully logged in.");
}
#Test
public void createUser() {
String expectedTitle = "User";
String actualTitle = driver.getTitle();
Assert.assertEquals(actualTitle, expectedTitle,"Title Not Found!");
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.findElement(By.xpath("//body/div[3]/div[2]/ul/li[2]/a/img")).click();
Error :
java.lang.AssertionError: Title Not Found! expected [User] but found []
This is because you are using Assert.
Assert.assertEquals(actualTitle, expectedTitle,"Title Not Found!");
Make use of Try catch in-order to proceed next step.
try{
Assert.assertEquals(actualTitle, expectedTitle,"Title Not Found!");
}catch (Exception e)
{
}