Screenshot on failed tests using Junit 5 Selenium parallel execution - java

I would like to take a screenshot every single time test fails or if multiple tests then multiple screenshots of course.
So far I understand that I can just wrap my single test with a try catch block and proceed taking a screenshot, however I would not want to wrap it in every test I have. I want it to apply to all of them without wrapping each one, do I have to do that in my setup?
public class WebDriverSettings
{
protected WebDriver driver;
protected String TARGET_URL;
#BeforeEach
public void setUp()
{
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver(new ChromeOptions().addArguments("window-size=1920x1480"));
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
loginToEnvironment();
}
}
public class LoginServiceTest extends WebDriverSettings
{
private LoginModal loginModal;
private AccountApi accountApi;
private Credentials credentials;
#BeforeEach
public void setUp()
{
super.setUp();
credentials = new SignUp();
accountApi = new AccountApi(credentials);
accountApi.createAccount();
loginModal = new HomePage(driver).acceptCookies().clickOnMyAccountTab().switchToLoginTab();
}
#Test
public void shouldSuccessfullyLogin()
{
try
{
accountApi.createAccount();
assertFalse(loginModal.login(credentials).getMyAccountName().getText().isEmpty());
} catch (Exception e)
{
try
{
File screenshotFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshotFile, new File("path"));
} catch (IOException ioException)
{
ioException.printStackTrace();
}
accountApi.closeAccount();
}
}
}
Solution advised by Jeff
So creating Util package and adding a class that would be responsible for creating a screenshot also it would generate random name but needs to be refactored i just made it quickly to make it work
public class ScreenShotCreator {
public static void takeScreenShot(WebDriver driver) {
try {
File screenshotFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshotFile, new File(fileNameGenerator()));
} catch (IOException e) {
throw new RuntimeException("Could not make a screenshot");
}
}
// creating this for test purposes , need to use string builder instead to append it instead of adding it
private static String fileNameGenerator() {
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy-HH:mm");
String path = ".....";
return path + "screenshot" + formatter.format(new Date()) + " " + RandomStringUtils.randomAlphanumeric(10) + ".png";
}
Then before closing it down just call the created method
#AfterEach
public void tearDown() {
ScreenShotCreator.takeScreenShot(driver);
driver.manage().deleteAllCookies();
driver.close();
driver.quit();
}

The solution that worked for me was to create this extension:
package some.thing;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.jupiter.api.extension.AfterTestExecutionCallback;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
public class Screenshotter implements AfterTestExecutionCallback {
private static final Logger LOG = LogManager.getLogger();
private static WebDriver driver;
public static void setDriver(WebDriver driver) {
Screenshotter.driver = driver;
}
#Override
public void afterTestExecution(ExtensionContext context) throws Exception {
if (context.getExecutionException().isPresent()) { // if the test execution has failed
String baseFileName = context.getRequiredTestClass().getSimpleName() + "-"
+ context.getRequiredTestMethod().getName()
+ LocalDateTime.now().format(DateTimeFormatter.ofPattern("-yyMMdd-HHmmss"));
File targetFile = new File("somewhere/" + baseFileName + ".png");
File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
Files.copy(scrFile.toPath(), targetFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
targetFile.setReadable(true, false);
LOG.info("Screenshot saved to " + targetFile.toPath());
}
}
}
Then apply it to the relevant test class like so:
#ExtendWith(Screenshotter.class)
public class SomeTest {
...
#BeforeAll
public void initialize() {
...
Screenshotter.setDriver(driver);
...
}
...
}

What I would suggest is
Create a method to take a screenshot and put that in a Utils class and call it when you want to take a screenshot. This will make taking a screenshot a lot easier because all the code lives in one place and can be easily called from anywhere.
Create a tearDown() method, if you don't have one already. Looks like it would go in the WebDriverSettings class from your currently posted code. Mark it with an #AfterEach annotation and then detect a failed test case and if it failed, take a screenshot.
If you aren't sure how to do that, there's a class in JUnit 4.9 and later called TestWatcher that you can use. There are lots of examples on the web on how to use it.

Related

Cannot invoke "io.restassured.specification.RequestSpecification.get(java.net.URI)

I'm learning to create a REST Assured and Cucumber framework from scratch following a tutorial video on Youtube.
Below is the step definition and the method it calls in the RestAssuredExtension class.
#Given("^I perform GET operation for \"([^\"]*)\"$")
public void i_Perform_GET_Operation_For(String url) throws Throwable {
RestAssuredExtension.GetOps(url);
}
package utilities;
import io.restassured.RestAssured;
import io.restassured.builder.RequestSpecBuilder;
import io.restassured.http.ContentType;
import io.restassured.response.Response;
import io.restassured.response.ResponseOptions;
import io.restassured.specification.RequestSpecification;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Map;
public class RestAssuredExtension {
public static RequestSpecification Request;
public RestAssuredExtension() {
//Arrange
RequestSpecBuilder builder = new RequestSpecBuilder();
builder.setBaseUri("http://localhost:3000/");
builder.setContentType(ContentType.JSON);
var requestSpec = builder.build();
Request = RestAssured.given().spec(requestSpec);
}
public static ResponseOptions<Response> GetOps(String url) {
//Act
try {
return Request.get(new URI(url));
} catch (URISyntaxException e) {
e.printStackTrace();
}
return null;
}
}
In the video tutorial, the test passes successfully. But when I run the test myself, it results in the following error:
Step failed
java.lang.NullPointerException: Cannot invoke "io.restassured.specification.RequestSpecification.get(java.net.URI)" because "utilities.RestAssuredExtension.Request" is null
at utilities.RestAssuredExtension.GetOps(RestAssuredExtension.java:42)
at steps.GETPostSteps.i_Perform_GET_Operation_For(GETPostSteps.java:21)
Any takers please?
From the example you have given, I think you have not initialized the RestAssuredExtension.Request field.
In the video (I quickly skimmed it), they provide a hook to create a new instance of the RestAssuredExtension before any tests are executed. This will ensure that the public static class variable Request will have been initialized to a non-null value.
My recommendation, if you want to reduce dependency for setup on the test framework and make use of static methods:
public final class RequestExtension {
private static RequestSpecification request;
// Ensure that no one is able to create an instance and thereby bypass proper initalization
private RequestExtension() {
}
// Ensures the initialization responsibility is within the class itself and not a hidden dependency for other users.
private static void getInstance() {
if (request == null) {
RequestSpecBuilder builder = new RequestSpecBuilder();
builder.setBaseUri("http://localhost:3000/");
builder.setContentType(ContentType.JSON);
var requestSpec = builder.build();
request = RestAssured.given().spec(requestSpec);
}
return request;
}
public static ResponseOptions<Response> GetOps(String url) {
// Initialize
getInstance();
// Act
try {
return request.get(new URI(url));
} catch (URISyntaxException e) {
e.printStackTrace();
}
return null;
}
}
Otherwise, mixing static methods with dependencies on the instance will keep tripping people up. Would go either with the above or remove static from the class altogether:
public class RequestExtension {
private RequestSpecification request;
public RestAssuredExtension() {
//Arrange
RequestSpecBuilder builder = new RequestSpecBuilder();
builder.setBaseUri("http://localhost:3000/");
builder.setContentType(ContentType.JSON);
var requestSpec = builder.build();
request = RestAssured.given().spec(requestSpec);
}
public ResponseOptions<Response> GetOps(String url) {
//Act
try {
return request.get(new URI(url));
} catch (URISyntaxException e) {
e.printStackTrace();
}
return null;
}
}
One thing to help with debugging is to follow Java naming conventions. The capitalisation of your class field RequestSpecification makes it read as a class not a field name. (Request vs request) It was the same in the video so its a source issue. :)

I can not passing variable to Main method (Cucumber)

I had tried to create method and call it from another file to the main class but It won't work the error message said "java.lang.NullPointerException"
Main.class
Keywords kw = new Keywords();
#When("^gmailDD$")
public void gmailDD() throws Throwable{
WebDriverWait wait5s = new WebDriverWait(driver, 5);
String regis = "/html/body/div[2]/div[1]/div[5]/ul[1]/li[3]/a";
String dd = "/html/body/div[1]/div/footer/div/div/div[1]";
String empty = "/html/body/div[1]/div/footer";
kw.clickbyxpath(regis);
String handle= driver.getWindowHandle();
System.out.println(handle);
// Store and Print the name of all the windows open
Set handles = driver.getWindowHandles();
System.out.println("Log window id: "+handles);
driver.switchTo().window("6442450949");
kw.clickbyxpath(empty);
kw.clickbyxpath(dd);
}`
Method.class
WebDriver saddriver;
public void clickbyxpath (String xpathvalue) throws InterruptedException, IOException
{
WebDriverWait sad = new WebDriverWait(saddriver, 10);
//To wait for element visible
System.out.println(xpathvalue);
String x = xpathvalue;
sad.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(x)));
wowdriver.findElement(By.xpath(x)).click();
}
I had tried to do the same coding in the same file, It has no problem but when I move Method.class to the new file, error message said "java.lang.NullPointerException" but I can get "xpathvalue" value.
This Error occur because of it will not able to find your driver instance.
refer below code snippet. this is not cucumber example but you can get idea by this.
Method.class
package testing.framework;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Method {
public WebDriver driver;
WebElement _clickForSearch;
public Method(WebDriver driver) {
this.driver = driver;
}
public Method clickByXpath(String xpathValues) {
WebDriverWait wait = new WebDriverWait(driver, 10);
_clickForSearch = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(xpathValues)));
_clickForSearch.click();
return this;
}
}
Testing.class
package testing.framework;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Testing {
public static WebDriver driver;
public static void main(String[] args) {
getWebDriver();
String xpathValues= "//div[#class='FPdoLc VlcLAe']//input[#name='btnK']";
Method m1 = new Method(driver);
m1.clickByXpath(xpathValues);
}
public static void getWebDriver() {
System.setProperty("webdriver.chrome.driver", "Your chrome driver path");
driver = new ChromeDriver();
driver.get("https://www.google.com");
}
}
You need to pass your driver instance to another.
So I would suggest you take the webdriver wait out of your method and instantiate it when instantiating your webdriver. I would then create methods like so:
Driver class
private final String USER_DIRECTORY = System.getProperty("user.dir");
private final int GLOBAL_TIMEOUT = 30;
private WebDriver webDriver;
private WebDriverWait webDriverWait;
public Driver(String browserName) {
this.browserName = browserName;
System.out.println(browserName);
switch (this.browserName.toUpperCase()) {
case "CHROME":
initializeChromeDriver();
break;
}
}
private void initializeChromeDriver() {
System.setProperty("webdriver.chrome.driver", USER_DIRECTORY.concat("\\drivers\\chromedriver.exe"));
webDriver = new ChromeDriver();
webDriver.manage().window().maximize();
webDriverWait = new WebDriverWait(webDriver, GLOBAL_TIMEOUT);
}
Click method
public void buttonClickByXpath(String xpath) {
try {
WaitForPreseneOfElement(xpath);
webDriver.findElement(By.xpath(xpath)).click();
} catch (Exception e) {
takeScreenshot();
AllureLog("Failed to click on the button object. Please check your xpath. | xpath used = " + xpath + "");
Assert.fail();
}
}
Test Class
Import your driver class
import Base.Driver;
Then you would need declair your driver class like so:
Driver driver;
Now you will have access to your method using
driver.buttonClickByXpath(//YourXpathHere)
The problem is "Method m1 = new Method(driver);" keyword,
I had coded this line outside the main method.
thank you very much, Sir

Selenium HtmlUnitDriver hangs randomly in random places

I used SeleniumHQ to record my actions and then exported them to Java Unity WebDrive. Then I edited exported code and added many small extra things like looping over array, time-stamps, etc.
My code does following:
Log into my site.
Goto my profile.
Delete my previous announcement.
Post new announcement.
Log out.
I have tried using FirefoxDriver and HtmlUnitDriver, but every single of them gives me this weird problem. My code start doing its work and randomly stops in random spot and hangs there forever.
For example it could log in -> goto profile -> delete previous and then stop, or it could hang right in the login. I loop over those steps over and over again, and more I loop more likely it is to get stuck.
First loops success rate is 90% second loop is around 40% etc. Also which Driver I use also affects this. It is most likely to hang with HtmlUnitDriver and I would really want to use HtmlUnitDrive because I want to run my code headless on Ubuntu Server.
Has anyone else had similar problems?
EDIT : Now after many hours of testing, I noticed that its only HtmlUnitDriver that hangs and not Firefox. When using Firefox I can see what it is doing and it is doing everything as it should. Problem occurs with HtmlUnitDriver.
And here is the code itself:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.concurrent.TimeUnit;
import org.junit.*;
import static org.junit.Assert.*;
import org.openqa.selenium.*;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
public class WebUpdater {
private WebDriver driver;
private String baseUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
#Before
public void setUp() throws Exception {
driver = new HtmlUnitDriver(true); // JavaScript enabled.
baseUrl = "http://exampleurl.com";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void testUnity() throws Exception {
openAndLogin();
gotoProfile();
deletePreviousPost();
uploadPost();
logOut();
System.out.println("Done!");
}
private void openAndLogin() {
driver.get(baseUrl);
driver.findElement(By.linkText("Login")).click();
driver.findElement(By.id("jsid-login-id")).clear();
driver.findElement(By.id("jsid-login-id")).sendKeys("bilgeis.babayan#gmail.com");
driver.findElement(By.id("jsid-login-password")).clear();
driver.findElement(By.id("jsid-login-password")).sendKeys("volume1991");
driver.findElement(By.cssSelector("input.right")).click();
}
private void gotoProfile() {
driver.findElement(By.cssSelector("img[alt=\"Profile\"]")).click();
}
private void deletePreviousPost() {
try {
driver.findElement(By.cssSelector("img[alt=\"ExampleName\"]")).click();
driver.findElement(By.linkText("Delete")).click();
assertTrue(closeAlertAndGetItsText().matches("^Confirm to delete this post[\\s\\S]$"));
} catch (Exception e) {
System.out.println(e);
}
}
private void uploadPost() {
driver.findElement(By.linkText("ExampleAction")).click();
driver.findElement(By.id("example_url")).clear();
driver.findElement(By.id("example_url")).sendKeys("Example text that gets typed in textfield.");
driver.findElement(By.cssSelector("input[name=\"example\"]")).clear();
driver.findElement(By.cssSelector("input[name=\"example\"]")).sendKeys("ExampleName");
driver.findElement(By.linkText("ExampleAction2")).click();
System.out.println("Done");
}
private void logOut() {
driver.get("http://exampleurl.com/logout");
System.out.println("Logged out.");
}
#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;
}
}
}
in my main class I call WebUpdater class like this:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Main {
public static void main(String[] args) {
Logger logger = Logger.getLogger("");
logger.setLevel(Level.OFF);
scan();
}
private static void scan() {
while (true) {
try {
// Test if connection is available and target url is up.
URL url = new URL("http://exampleurl.com");
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
urlConn.connect();
// Start tests.
WebUpdater updater = new WebUpdater();
updater.setUp();
updater.testUnity();
updater.tearDown();
} catch (Exception ex) {
System.out.println(ex);
}
try {
Thread.sleep(12000);
} catch (InterruptedException e) {
}
}
}
}
I had a bad experience with HtmlUnitDriver. Some time ago I wrote testing framework which were supposed to be fired at Hudson, and finally I decided to use Firefox driver which was more predictable and easier to debug. The point is that in my case it was a page full of javascripts - dynamically loaded fields, etc., and working with HtmlUnitDriver was really a can of worms.
If you really need to use HtmlUnitDriver try do debug 'pagesource' which is accessible for Selenium in 'current' (hanging) moment.
HtmlUnit 2.11 is flawed (see here and here), and since HtmlUnit 2.12 went live march 6th, the current version of HtmlUnitDriver is probably still based on HtmlUnit 2.11.
If you post your "http://exampleurl.com/" source code (or just give me a working url to the page if it's public) I could run the page with scripts through HtmlUnit 2.12.

run selenium IDE exported test case

I am new to the world of testing. I am using selenium IDE for recording the tests. Also, I am exporting the test case as JUnit4 test case. My export looks like:
package com.example.tests;
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 Test {
private WebDriver driver;
private String baseUrl;
private StringBuffer verificationErrors = new StringBuffer();
#Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = "http://192.168.8.207/";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void test() throws Exception {
driver.get(baseUrl + "/");
driver.findElement(By.name("user")).clear();
driver.findElement(By.name("user")).sendKeys("admin");
driver.findElement(By.name("password")).clear();
driver.findElement(By.name("password")).sendKeys("infineta123");
driver.findElement(By.id("btnLogin-button")).click();
}
#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;
}
}
}
How to execute this test case? Now after that, how can I automate the execution of several such test cases?
Use this code as runner for your tests.
import org.junit.runner.JUnitCore;
import com.example.tests;
public static void main(String[] args) {
Result result = JUnitCore.runClasses(Test.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
}
Test.class is the file name(Test) containing the code for tests. You can add List of Classes if you have multiple test cases.
Look at this page: http://code.google.com/p/selenium/wiki/UsingWebDriver
You will probably have to download the selenium and import it to the project.
If this is done, you can go to the "Test" - it depends on developement tool you are using - In NetBeans I do it via Run - Test File (Ctrl + F6 I think)

How to not Hard code the program in java? Used property file. But unable to use it with multiple xpaths?

Scenario: Download a new month report from the site.
Month.txt: Oct(2015) Unconventional wells
Here is the structure:
config.properties:
#browser
browser=http://www.depreportingservices.state.pa.us/ReportServer/Pages/ReportViewer.aspx?%2fOil_Gas%2fOil_Gas_Well_Historical_Production_Report
#drop-down box
list_box= .//*[#id='ReportViewerControl_ctl04_ctl03_ddValue']
#view report button
view_report = .//*[#id='ReportViewerControl_ctl04_ctl00']
#save button
save_button = .//*[#id='ReportViewerControl_ctl05_ctl04_ctl00_Button']
#csv button
csv_button = .//*[#id='ReportViewerControl_ctl05_ctl04_ctl00_Menu']/div[2]/a
#read path
read_path = E:\\Ashik\\wkspSelenium\\PropertyPractice\\src\\package1\\Month.txt
#write path
write_path = E:\\Ashik\\wkspSelenium\\PropertyPractice\\src\\package1\\Month.txt
Implementation.java:
package package1;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
import java.util.Properties;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import package1.Fileaccessing;
public class Implementaion {
public static WebDriver driver;
public FileInputStream fis;
public static String propertyfilepath="config.properties";
public String browserName;
//To get a key value from property file
public String getProperty(String key) throws IOException, FileNotFoundException{
fis=new FileInputStream(propertyfilepath);
Properties prop=new Properties();
prop.load(fis);
return prop.getProperty(key);
}
public static void initiate_webdriver() throws IOException
{
// Changing default file downloading location path using the FirefoxProfile.setpreference method.
FirefoxProfile fprofile = new FirefoxProfile();
fprofile.setPreference("browser.download.folderList",2);
fprofile.setPreference("browser.download.manager.showWhenStarting",false);
//file download path
fprofile.setPreference("browser.download.dir", "E:\\"); //need to ask muthu
//CSV format to download the data
fprofile.setPreference("browser.helperApps.neverAsk.saveToDisk", "text/csv");
//Automatically downloads the file without manual selection
fprofile.setPreference("browser.helperApps.alwaysAsk.force",false);
fprofile.setPreference("browser.download.manager.showAlertonComplete",false);
fprofile.setPreference("browser.download.manager.closeWhenDone",false);
//Assigning the created profile to Firefox driver
WebDriver driver=new FirefoxDriver(fprofile);
}
//To get a url in browser
public static void get_url(String link) throws InterruptedException
{
driver.get(link);
driver.manage().window().maximize();
}
//To select a value by visible text in a drop down
public static void downloads_new_month(String xpath, String value) throws InterruptedException
{
WebElement mSelectElement = driver.findElement(By.xpath(xpath));
List<WebElement> optionsList = mSelectElement.findElements(By.tagName("option"));
Fileaccessing fileAccessObject = new Fileaccessing();
//Reading txt from the Month txt file
String oldMonth = fileAccessObject.getTheOldMonthFromFile(propertyfilepath);
System.out.println("The old month is: " + oldMonth);
String newMonth ="";
for (int i = 2; i < optionsList.size(); i++) {
WebElement element = optionsList.get(i);
newMonth = element.getText();
//Message that prints the new month
System.out.println("The new month is:"+newMonth);
/*Condition to check if the New month is equal to Old month, if it is not equal then proceeds
* to download that particular month data or else breaks the loop
*/
if (oldMonth.equals(newMonth)) {
System.out.println("No new months are available to download");
driver.close();
break;
}else if (i==2 & !(oldMonth.equals(newMonth))) {
//else if (!(oldMonth.equals(newMonth))) {
element.click();
//Click on View Report button
driver.findElement(By.xpath(xpath)).click();
//Wait time to load the selected month data
Wait(20000);}
public static saveButton(String xpath2 , String value2) throws InterruptedException{
//Click on File save button
driver.findElement(By.xpath(xpath2)).click();
//wait time to load the File format options
Wait(20000); }
public static void csvButton(String xpath3 , String value3) throws InterruptedException{
//Click on csv format button
driver.findElement(By.xpath(xpath3)).click();
Wait(10000);
//Success message to indicate that the data is downloaded successfully in csv format
System.out.println("New Month data downloaded in csv format:" + newMonth);
}
//Saves the new month txt to the file
public static void save_new_month() {
fileAccessObject.saveIntoAFile(newMonth, propertyfilepath);
//closes the web page once the file is downloaded
driver.close();
break;
}
} }
public static void Wait(int time){
try {
Thread.sleep(time);
} catch (Exception e) {
// TODO: handle exception
} }
}
I have successfully set up browser initialization and opening, now how to use it in download_new_month method, as there are 3 xpath's has to be clicked to download a report when condition is met. Please help.
At the starting of the class used below one
public static WebDriver driver;
again in public static void initiate_webdriver() method, using
WebDriver driver=new FirefoxDriver(fprofile);
looks not correct here, already driver is declared globally, so please use
driver=new FirefoxDriver(fprofile);
in initiate_webdriver() method.
Thank You,
Murali

Categories