IllegalStateException when running a Selenium test - selenium-webdriver

I'm getting an IllegalStateException thrown when running the following code:
package newprojectss;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Tours {
public static void main(String[] args) {
// declaration and instantiation of objects/variables
System.setProperty("webdriver.chrome.driver","C:\\selenium-2.25.0\\chromedriver_win32");
WebDriver driver = new ChromeDriver();
String baseUrl = "http://demo.guru99.com/test/newtours/";
String expectedTitle = "Welcome: Mercury Tours";
String actualTitle = "";
// launch Fire fox and direct it to the Base URL
driver.get(baseUrl);
// get the actual value of the title
actualTitle = driver.getTitle();
/*
* compare the actual title of the page with the expected one and print
* the result as "Passed" or "Failed"
*/
if (actualTitle.contentEquals(expectedTitle)){
System.out.println("Test Passed!");
} else {
System.out.println("Test Failed");
}
//close Firefox
driver.close();
}
}
What can cause the problem?

illegalstateexception occurs because the chrome driver is not set properly
System.setProperty("webdriver.chrome.driver","C:\\selenium-2.25.0\\chromedriver_win32")
Chrome driver path doesn't point till chromedriver.exe file
Unzip your driver folder and point the location till chromedriver.exe
Eg: C://Users//username//Desktop//chromedriver.exe

Related

cannot find Opera binary error selenium+java using webdrivermanager

while running the below program in eclipse, got an error "cannot find Opera binary".
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.opera.OperaDriver;
import io.github.bonigarcia.wdm.WebDriverManager;
public class Opera
{
public static void main(String[] args)
{
WebDriverManager.operadriver().setup();
WebDriver d = new OperaDriver();
d.get("http://amazon.ae");
d.close();
}
}
How to solve this , please help..
Try to specify the path of your Opera launcher binary:
String operaBinary = "C:\\Program Files\\Opera\\launcher.exe"; // If Windows
WebDriverManager.operadriver().setup();
OperaOptions options = new OperaOptions();
options.setBinary(operaBinary);
WebDriver driver = new OperaDriver(options);
// ...

What is the use of System.getProperty() while taking Screenshot in Selenium?

I'm running a program for adding screenshot in extent report automatically using selenium. Program is running perfectly,but I want to know the meaning of System.getProperty line in below program .
public class SST
{
public static String getScreenshot(WebDriver driver)
{
TakesScreenshot ts=(TakesScreenshot) driver;
File src=ts.getScreenshotAs(OutputType.FILE);
String path = System.getProperty("user.dir")+"/Screenshot/"+System.currentTimeMillis()+".png";
File destination=new File(path);
try
{
FileUtils.copyFile(src, destination);
} catch (IOException e)
{
System.out.println("Capture Failed "+e.getMessage());
}
return path;
}
}
It is getting the user home directory, for example, C:\Users\user10796675.

Selenium-Extent_Reports: Not able to view the failure screenshots on other Computer/Machine

-Failure Screenshot are visible in Extent_Reports on my local machine. But not able to view the failure screenshot in Extent_Reports on other Computer/Machine.
-When i trigger build from Jenkins, After build successful, Sending email to:Recipient List
To Capture Screenshot
public String captureScreen(String fileName) {
if(fileName =="") {
fileName="Screenshot"; }
File destFile=null;
Calendar calendar =Calendar.getInstance() ;
SimpleDateFormat formater= new SimpleDateFormat("dd_MM_yyy_hh_mm_ss");
File srcFile=((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
try {
String reportDirectory = "/src/main/java/com/test/automation/Demo/screenshot/";
//String reportDirectory= new File(System.getProperty("user.dir")).getAbsolutePath()+"./src/main/java/com/test/automation/Demo/screenshot/";
destFile= new File((String)reportDirectory + fileName +"-" + formater.format(calendar.getTime())+ ".png");
FileUtils.copyFile(srcFile,destFile );
//This will help us to link screen shot in Extent report
Reporter.log("<a href='"+destFile+ "'><img src='" +destFile+"' height='100' width='100'/></a>");
//Reporter.log("<a href='"+destFile.getAbsolutePath()+ "'><img src='" +destFile.getAbsolutePath()+"' height='100' width='100'/></a>");
}
catch(IOException e) {
e.printStackTrace();
}
return destFile.toString();
}
For generating Extent reports with screenshots for Failure test cases
public void getresult(ITestResult result) {
if(result.getStatus()==ITestResult.FAILURE)
{
test.log(LogStatus.ERROR, result.getName()+" Test case FAILED due to below issues: "+result.getThrowable());
String screen = captureScreen("");
test.log(LogStatus.FAIL," Failure Screenshot : "+ test.addScreenCapture(screen));
}}
If You're using remoteWebDriver than it must be augmented before you can use the screenshot capability. Did You try to
WebDriver driver = new RemoteWebDriver();
driver = new Augmenter().augment(driver);
// or for mobile driver
androidDriver.setFileDetector(new LocalFileDetector());
//this is needed when using remoteDriver
Here is how I take screenshot for ExtentReport
File scrFile = driver.getScreenshotAs(OutputType.FILE);
String dest = System.getProperty("user.dir") + "/resources/screenshots/" + dataMethod.getAndroidDriver().getSessionId() + ".png";
File destination = new File(dest);
try {
FileUtils.copyFile(scrFile, destination);
// this is just utility which takes screenshot and copy it to desired destination
dataMethod.setScreenshotPath(destination.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
}
And on code failure:
#Override
public synchronized void onTestFailure(ITestResult result) {
setTestEndTime(result);
ExtentTest extentTest = methodData.getExtentTest();
extentTest.addScreenCaptureFromPath(methodData.getScreenshotPath());
}
Hope this will help.
I didn't used Extent reports, i have my own implementation for reports. But i am expecting is there is issue with src
<img src='" +destFile+"' height='100' width='100'/></a>");
Here, destFile brings location of image or screenshot which is related to your machine. the same should not be works for others. We have to use relative path, see this
https://www.w3schools.com/html/html_filepaths.asp
And also make sure that when sharing reports, it should contains all requires files and folders also.
Normally, the issue happens as the local files are not allowed to be loaded. So even we put relative or absolute path, that seems not work for many cases.
So I try to take base64screenshot instead, and it displays quite good in Extent Report.
To have the screenshot in folder report, just need to take screenshot as usual.
public static String getBase64Screenshot(WebDriver driver, String screenshotName) throws IOException {
String encodedBase64 = null;
FileInputStream fileInputStream = null;
TakesScreenshot screenshot = (TakesScreenshot) driver;
File source = screenshot.getScreenshotAs(OutputType.FILE);
String destination = windowsPath + "\\FailedTestsScreenshots\\"+screenshotName+timeStamp+".png";
File finalDestination = new File(destination);
FileUtils.copyFile(source, finalDestination);
try {
fileInputStream =new FileInputStream(finalDestination);
byte[] bytes =new byte[(int)finalDestination.length()];
fileInputStream.read(bytes);
encodedBase64 = new String(Base64.encodeBase64(bytes));
}catch (FileNotFoundException e){
e.printStackTrace();
}
return encodedBase64;
}
Call it in failure cases:
public synchronized void onTestFailure(ITestResult result) {
System.out.println("==="+methodDes + "=== failed!");
try {
WebDriver driver = (WebDriver) result.getTestContext().getAttribute("driver");
String base64Screenshot = ExtentManager.getBase64Screenshot(driver, result.getName());
MediaEntityModelProvider mediaModel = MediaEntityBuilder.createScreenCaptureFromBase64String(base64Screenshot).build();
test.get().fail("image:", mediaModel);
} catch (IOException e) {
e.printStackTrace();
}
test.get().fail(result.getThrowable().getMessage());
}

Strange behaviour in code exection in java

I face strange execution behaviors in login test methods. I run this code Under selenium Grid. and Grid is configured as a standalone server. So, first I start the selenium grid(Hub\Node) using the batch file to execute by tests.
Following is my class and specs.
code:
1. pojDataSource.java:
public class pojDataSource {
private static WebElement element = null;
private static List<WebElement> elements = null;
public static WebElement txt_UserName(WebDriver driver){
driver.findElement(By.id("txtUserName")).clear();
element = driver.findElement(By.id("txtUserName"));
return element;
}
public static WebElement txt_Password(WebDriver driver){
driver.findElement(By.id("txtPassword")).clear();
element = driver.findElement(By.id("txtPassword"));
return element;
}
}
clsConstant.java:
public class clsConstant {
public static final String URL = "http://localhost:1234/";
public static final String Username = "username";
public static final String Password = "password";
}
ModuleTest.java:
public class ModuleTest {
public RemoteWebDriver mDriver = null;
public DesiredCapabilities mCapability = new DesiredCapabilities() ;
public WebElement mWebElement = null;
public String mBaseURL = clsConstant.URL;
public static clsExcelSampleData mAddConnectorXls;
#Test
public void beforeMethod() throws Exception {
WebDriverWait wdw =null;
mCapability.setCapability("platform", org.openqa.selenium.Platform.WINDOWS);
mCapability = DesiredCapabilities.firefox();
mCapability.setVersion("45.0.2");
mDriver = new RemoteWebDriver(new URL("http://127.0.0.1:4444/wd/hub/"), mCapability);
mDriver.get(mBaseURL);
mDriver.manage().window().maximize();
pojDataSource.txt_UserName(mDriver).sendKeys(clsConstant.Username ) ;
pojDataSource.txt_Password(mDriver).sendKeys(clsConstant.Password ) ;
pojDataSource.btn_LogIn(mDriver).click();
}
When I execute the code in DEBUG mode in eclipese IDE it shows me the strange behaviors. First it start browser and open the mBaseURL successful with login screen. After loading page it shows default userName\password in browser.
Now when debug point comes to pojDataSource.txt_UserName(mDriver).sendKeys(clsConstant.Username ); line. By pressing F5 my debug point goes to pojDataSource.txt_Password(); line and it fetch wrong password and script execution fails. I worry about how this will be happens if my debug point is at username but still it goes to fetch value of password?
Tried solutions:
1. As I use Firefox browser to run test. I clear my password from browser catch.
Recheck the WebElements IDs and make sure they are reachable by WebDriver while debugging. Also try to avoid using 'static' to WebElements. Take a look on Page Objects Pattern.

What does 'moveFailed' really do?

I want to create a file input that behaves as follows:
Process the exchange
Attempt to copy the input file to a shared drive
If step (2) fails (e.g. share is down) then move to local file instead
Following the doc the 'moveFailed' parameter allows to "set a different target directory when moving files after processing (configured via move defined above) failed". So this sounds like the moveFailed would cover step (3).
The following test, however fails...what am I doing wrong ? I am using camel 2.10.0.fuse.
package sandbox.camel;
import java.io.File;
import org.apache.camel.Endpoint;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.junit.Test;
public class MoveFailedTest extends org.apache.camel.test.junit4.CamelTestSupport {
private String failedDir = "move-failed";
#Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
#Override
public void configure() throws Exception {
from("file:tmp/prepare").to("file:tmp/input");
from("file:tmp/input?move=/doesnotexist&moveFailed=" + failedDir).to("file:tmp/output");
}
};
}
#Test
public void test_move() throws Exception {
// arrange
File moveFailedDir = new File("tmp/input/" + failedDir);
moveFailedDir.mkdirs();
File[] failedCount1 = moveFailedDir.listFiles();
failedCount1 = failedCount1 == null ? new File[0] : failedCount1;
String messagePayload = "Hello";
Endpoint input = getMandatoryEndpoint("file:tmp/prepare");
MockEndpoint output = getMockEndpoint("mock:file:tmp/output");
output.setMinimumExpectedMessageCount(1);
output.expectedBodiesReceived(messagePayload);
// act
template.asyncSendBody(input, messagePayload);
Thread.sleep(3000);
// assert: only 1 output
assertMockEndpointsSatisfied();
// assert: renamed failed, hence input file was moved to 'movefailed' directory
File[] failedCount2 = moveFailedDir.listFiles();
assertEquals("No file appeared in 'movefailed' directory", failedCount1.length + 1, failedCount2.length);
}
}
Your test is most likely wrong. The autocreate option is default true, which means directories is created if needed.

Resources