Reputation: 1
Could someone help me in the below situation?
I've to create a common method to get screenshots using Selenium Webdriver where the file name of the screenshot should get updated as the name of the method where I call it.
This is what I have now:
Created a method to get the Timestamp and use it to the file name:
public String getTimeStamp() {
String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());
return timestamp;
}
// Method to get the Screenshot at any given instance. The Screenshots taken are copied to Screenshots folder under `"build\jbehave\view"`.
public void getScreenShots() throws Exception {
File srcfile = driver.getScreenshotAs(OutputType.FILE);
File folder = new File("Screenshots");
if(folder.exists()){
FileUtils.copyFile(srcfile, new File("./build/jbehave/view/Screenshots/" + "Screenshot_" + getTimeStamp() + ".png"));
}else {
File dir1 = new File("Screenshots");
dir1.mkdir();
FileUtils.copyFile(srcfile, new File("./build/jbehave/view/Screenshots/" + "Screenshot_" + getTimeStamp() + ".png"));
}
}
I'm looking for a method which can get the name of the methods where I call the above getScreenShots()
method and have it as my file name in run time instead of having Timestamps.
Upvotes: 0
Views: 2148
Reputation: 333
You can use this to get the method of the running test. And then use the selenium driver to get the screenshot.
Upvotes: 0
Reputation: 769
You can get method name from stack trace of current thread:
byte[] scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.BYTES);
String filename = Thread.currentThread().getStackTrace()[1].toString();
FileUtils.writeByteArrayToFile(new File(filename), scrFile);
In this example, the filename
is a method, which executes this fragment (it is 1 in stack trace).
Upvotes: 2