I am trying hard to run my Selenium Test not local but in a grid.
I thought I am doing good but I don´t get it to run.
HUB and NODE are Up and running(started with CMD) and I am using the right IP adresses.
Please let me know what I am doing wrong! Do you think it maybe could be a problem with a proxy?
Greetings Arno (student from Germany)
// Import all the stuff I need
public class MpreisScreenshot_ID {
private String baseUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
#BeforeClass(alwaysRun = true)
public void setUp() throws Exception {
String requiredBrowser = "firefox";
}
//the "if" underneath is just for a selection (to make it better to read
// I deleted the others)
if (requiredBrowser == "firefox")
{
DesiredCapabilities capabilityFirefox = DesiredCapabilities.firefox();
capabilityFirefox.setBrowserName("firefox");
capabilityFirefox.setVersion("54");
WebDriver driver= new RemoteWebDriver(new
URL("http://***.***.***.**:4445/grid/register"),capabilityFirefox);
}
baseUrl = "http://*****/****";
// driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
}
WebDriver driver;
#Test
public void captureScreenshot() throws Exception
{
//Start of Selenium test
// Maximize the browser
driver.manage().window().maximize();
// deleted all the steps
#AfterMethod
public void tearDown(ITestResult result)
{
// Test failing or Passing?
if(ITestResult.FAILURE==result.getStatus())
{
try
{
// Create reference of TakesScreenshot
TakesScreenshot ts=(TakesScreenshot)driver;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss");
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
String uhrzeit= sdf.format(timestamp);
// Call method to capture screenshot
File source=ts.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(source, new File("D:\\DATA\\Selenium\\TestNG-
Screenshots\\"+result.getName()+uhrzeit+".png"));
System.out.println("Screenshot taken");
}
catch (Exception e)
{
System.out.println("Exception while taking screenshot "+e.getMessage());
}
}
// close application
driver.quit();
}
}
Check your url, usually the default port for the Selenium Hub is 4444, also try the following:
http://youripaddress:4444/wd/hub/
Related
When i am trying to run my selenium tests the first test seem to work correctly but then i am recieving this error for the subsequent tests, Im after switching my tests over to an electron app so not sure if this is after causing a issue :
org.openqa.selenium.NoSuchSessionException: Session ID is null. Using WebDriver after calling quit()?
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:17:03'
My set up page is:
public class SetUp extends TestRail {
private static ChromeDriver browser;
public static String urlHost;
public static String testEnv;
public static PageConfig pageConfig;
#Before
public void initialBrowser() {
if(browser == null) {
String projectLocation = System.getProperty("user.dir");
System.setProperty("webdriver.chrome.driver", projectLocation + "/chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("--no-sandbox");
options.addArguments("--disable-dev-shm-usage");
options.addArguments("start-maximized");
options.addArguments("--disable-gpu");
options.addArguments("disable-infobars");
System.setProperty("webdriver.chrome.silentOutput", "true");
options.setBinary("C:/Users/ElectronApp.exe");
browser = new ChromeDriver(options);
//--------------------
pageConfig = new PageConfig(browser);
}
}
//method: To get the url configs for the environment used to run the test
//#parameter: dev or test. demo doesn't not have a separate front end url
public void beforeTest(#NotNull final String env) throws Exception {
testEnv = env;
System.out.println("TEST ENVIRONMENT: " + testEnv);
switch (env){
case "qa-84" :
urlHost = "http://ukdc1-docker-mx:84/qa/#/login";
break;
case "qa-85":
urlHost = "http://ukdc1-docker-mx:85/qa/#/login";
break;
default:
throw new Exception("Incorrect environment passed");
}
}
//method to close the browser after every cucumber scenario
#After
public void closeBrowser(Scenario scenario) throws IOException, APIException {
if(scenario.isFailed()){
try{
TakesScreenshot screenshot = (TakesScreenshot)browser;
File source = screenshot.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(source, new File("logs/screenshots/" + scenario.getName() + ".png"));
System.out.println("Screenshot taken");
} catch (Exception e){
System.out.println("Exception while taking screenshot " + e.getMessage());
}
}
browser.quit();
writeResultToTestRail(scenario);
}
public void writeResultToTestRail(Scenario scenario) throws IOException, APIException {
String tesCaseID = new String();
for(String s: scenario.getSourceTagNames()){
if(s.contains("TestRail")){
int size = s.length();
int startOfID = s.indexOf('"');
tesCaseID = s.substring(startOfID + 1,size - 2);
}
Map data = new HashMap();
if(scenario.isFailed()){
data.put("status_id", 5);
data.put("comment", "Test Env: " + urlHost + "\n\n" + logError(scenario));
}else {
data.put("status_id", 1);
}
postTestCaseStatus("add_result_for_case/","3914", tesCaseID, data);
//3914
}
}
protected void getTestCaseDetailsInConsole(String testCaseId) throws IOException, APIException {
System.out.println(getTestCaseDetails(testCaseId));
}
private static String logError(Scenario scenario) {
try {
Class klass = ClassUtils.getClass("cucumber.runtime.java.JavaHookDefinition$ScenarioAdaptor" );
Field fieldScenario = FieldUtils.getField(klass, "scenario", true);
if (fieldScenario != null) {
fieldScenario.setAccessible(true);
Object objectScenario = fieldScenario.get(scenario);
Field fieldStepResults = objectScenario.getClass().getDeclaredField("stepResults" );
fieldStepResults.setAccessible(true);
ArrayList<Result> results = (ArrayList<Result>) fieldStepResults.get(objectScenario);
for (Result result : results) {
if (result.getError() != null) {
System.out.println(result.getError() + "\n\n" + result.getErrorMessage());
if(result.getErrorMessage().length() > 3100) {
return result.getErrorMessage().substring(0, 3100);
} else {
return result.getErrorMessage();
}
}
}
}
return "Fetching error logs from the scenario ran into some issue, please check jenkins logs";
} catch (IllegalAccessException | NoSuchFieldException | ClassNotFoundException e) {
return e.getMessage();
}
}
}
And My Page config:
public class PageConfig {
public ChromeDriver browser;
public PageConfig(ChromeDriver browser){
this.browser = browser;
}
//method: Get instance method can be called on any class, it helps to avoid to add a line every time a new PO is added to the project.
//#parameter: ClassName.class
//#example: PageConfig.GetInstance(LoginPage.class).onLoginPage(); where onLoginPage is an method of
LoginPage.
public <TPage extends BasePage> TPage GetInstance (Class<TPage> pageClass){
try {
return initElements(browser, pageClass);
}catch(Exception e){
e.printStackTrace();
throw e;
}
}
}
the error shows that your driver close before the execution of the code, so the code of #After is directly executed so what I think is that you forget to use #Test in your set up page because there is #Before and #After but I don't see #Test.
Hi community: I'm facing the next issue: I'm working with Cucumber, Selenium WebDriver using Page Factory. The error getting here is from the Step Definition side:
java.lang.NullPointerException
at pages.page_First.startNavigation(page_First.java:33)
at stepdefs.stepdefs_First.iGoToGoogle(stepdefs_First.java:20)
at ✽.I go to Google (file:src/test/resources/features/first.feature:10)
This is the part of the code (StepDefinition) where issue occurs:
#Given("I go to Google")
public void iGoToGoogle() {
page_first.startNavigation();
}
From the Page side, this is the code:
public class page_First extends BasePage {
public page_First() {
PageFactory.initElements(driver, this);
}
///////////////////////WEB ELEMENTS///////////////////////
#FindBy(name = "q")
private WebElement searchText;
#FindBy(name="btnK")
private WebElement searchButton;
//////////////////////BASE METHODS//////////////////////
public void startNavigation() {
driver.get(PropertyManager.getInstance().getURL());
}
public void search(String search) {
setTextAs(searchText, search);
}
public void enterButton (){
clickElement(searchButton);
}
}
The feature file:
Scenario Outline: Search google.com to verify google search is working
Given I go to Google
When I query for "<search>" cucumber spring selenium
And click search
Then google page title should become the first page
Examples:
| search |
| Cucumber Selenium |
This is my Browser class:
public class Browser {
// Take the instance of WebDriver
public static WebDriver driver;
public WebDriver initializeBrowser() throws IOException {
//Properties taken from config.properties
String browser = PropertyManager.getInstance().getBrowser();
if(browser.equals("chrome")) {
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
} else if(browser.equals("firefox")) {
WebDriverManager.firefoxdriver().setup();
driver = new FirefoxDriver();
} else if(browser.equals("ie")) {
WebDriverManager.iedriver().setup();
driver = new InternetExplorerDriver();
} else if(browser.equals("edge")) {
WebDriverManager.edgedriver().setup();
driver = new EdgeDriver();
} else if(browser.equals("opera")) {
WebDriverManager.operadriver().setup();
driver = new OperaDriver();
} else {
System.setProperty("webdriver.safari.driver","/usr/bin/safaridriver");
driver = new SafariDriver();
}
System.out.println("-----> Proceed to initialize driver <-----");
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.manage().window().maximize();
return driver;
}
}
and here is my configuration property reader class:
public class PropertyManager {
private static PropertyManager instance;
private static final Object lock = new Object();
private static String propertyFilePath = System.getProperty("user.dir") + "//src//main//resources//data//config.properties";
///////////////////////////// DATA IN PROPERTIES //////////////////////////
private static String url;
private static String browser;
//Create a Singleton instance. We need only one instance of Property Manager.
public static PropertyManager getInstance () {
if (instance == null) {
synchronized (lock) {
instance = new PropertyManager();
instance.loadData();
}
}
return instance;
}
//Get all configuration data and assign to related fields.
private void loadData() {
//Declare a properties object
Properties prop = new Properties();
//Read config.properties file
try {
prop.load(new FileInputStream(propertyFilePath));
} catch (IOException e) {
System.out.println("Configuration properties file cannot be found");
}
//Get properties from config.properties
url = prop.getProperty("url");
browser = prop.getProperty("browser");
}
public String getURL () {
return url;
}
public String getBrowser () {
return browser;
}
}
I was forgetting this, my Step Definition class:
public class stepdefs_First {
private page_First page_first = PageFactory.initElements(Browser.driver, page_First.class);
#Given("I go to Google")
public void iGoToGoogle() {
page_first.startNavigation();
}
#When("I query for {string} cucumber spring selenium")
public void iQueryForCucumberSpringSelenium(String search) throws Exception {
page_first.search(search);
}
#And("click search")
public void clickSearch() {
page_first.enterButton();
}
#Then("google page title should become the first page")
public void googlePageTitleShouldBecomeTheFirstPage() {
System.out.println("All OK");
}
}
By the way, this is my config.properties
browser = firefox
url = https://www.google.cl
Please I need your help.
Initialize the Page Object class
page_First page_first=new page_First();
i am Unable to Have separate Logs/entries for Different Test Cases. i.e Logs are Getting Appended on to a Single Test Case in the Extent Report generated.
Using Extent Report Version 2.41.1..
The Report Sample:
MY Code Goes like This:
Base Class of TestNG:
public static ExtentReports report;
public static ExtentTest logger;
#BeforeSuite
#Parameters({"BrowserName"})
public void beforeSuite(#Optional("Firefox") String BrowserName)
{
date = new Date();
SimpleDateFormat ft = new SimpleDateFormat ("dd-MM-yyyy");
String TodaysDate = ft.format(date);
prop = ResourceBundle.getBundle("DataFile");
Driver = Browser_Factory_FSQA_Class.getBrowser(BrowserName);
path = "//home//workspace//....//FSQA.ExtentReports//FSQA_ExtentReport_" + TodaysDate;
File f=new File(path);
if(!f.exists())
{
report = new ExtentReports(path);
}
}
#BeforeTest
#Parameters({"BrowserName"})
public void SetUpConfig(#Optional("Firefox") String BrowserName)
{
report = new ExtentReports(path, false,DisplayOrder.NEWEST_FIRST);
report.loadConfig(new File("//home//......//extent-config.xml"));
report.addSystemInfo("Build-Tag", prop.getString("Build-Tag"))
.addSystemInfo("Selenium ", prop.getString("SelVer"))
.assignProject(prop.getString("Application"))
.addSystemInfo("Envirnoment", prop.getString("AppEnvirnoment"))
.addSystemInfo("Extent", prop.getString("ExtRpVer"));
logger = report.startTest(this.getClass().getSimpleName());
logger.log(LogStatus.INFO,this.getClass().getSimpleName() +" will Run on "+ BrowserName +" Browser");
Driver.get(prop.getString("URL"));
Driver.manage().window().maximize();
Driver.manage().window().maximize();
Driver.manage().timeouts().implicitlyWait(45, TimeUnit.SECONDS);
}
#AfterMethod(alwaysRun=true)
public void afterMethod(ITestResult result) throws IOException
{
try
{
if(result.getStatus()==ITestResult.FAILURE)
{
String res = captureScreenshot(Driver, result.getName());
String image= logger.addScreenCapture(res);
System.out.println(image);
String TestCaseName = this.getClass().getSimpleName() + " Test Case Failure and Title/Boolean Value Failed";
logger.log(LogStatus.FAIL, TestCaseName + logger.addScreenCapture(res));
}
else if(result.getStatus()==ITestResult.SUCCESS)
{
logger.log(LogStatus.PASS, this.getClass().getSimpleName() + " Test Case Success and Title Verified");
}
else if(result.getStatus()==ITestResult.SKIP)
{
logger.log(LogStatus.SKIP, this.getClass().getSimpleName() + " Test Case Skipped");
}
}
catch(Throwable t)
{
logger.log(LogStatus.ERROR,t.getMessage());
}
}
public String captureScreenshot(WebDriver Driver, String TestName)
{
try
{
date = new Date();
SimpleDateFormat ft = new SimpleDateFormat ("dd_MM_yyyy");
String TodaysDate = ft.format(date);
TakesScreenshot ts=(TakesScreenshot)Driver;
File source=ts.getScreenshotAs(OutputType.FILE);
Sc_Destination = prop.getString("SC_Dest")+TestName+"__"+TodaysDate+".png";
FileUtils.copyFile(source,new File(Sc_Destination));
logger.log(LogStatus.FAIL,image, "Title verification");*/
return Sc_Destination;
}
catch (Exception e)
{
System.out.println("Exception while taking screenshot "+e.getMessage());
}
return Sc_Destination;
}
#AfterTest(alwaysRun=true)
public void AfterTest()
{
Driver.close();
report.endTest(logger);
report.flush();
}
#AfterSuite
public void AfterSuite()
{
report.close();
Driver.quit();
}
My Tests are Separate Clases which Extends this Base Class:
TC1:
public classTC1 extends BaseTestNG
{
#Test(groups = {"Happy_Path"} , description="TC1")
public void TestCase1() throws InterruptedException, Exception
{
logger.log(LogStatus.INFO, " Test Case2 Block Entered");
Thread.sleep(4000);
......
......
logger.log(LogStatus.INFO, "Assert Flag Received");
Thread.sleep(4000);
Assert.assertTrue(AssertFlag);
}
}
TC2:
public classTC2 extends BaseTestNG
{
#Test(groups = {"Happy_Path"} , description="TC2")
public void TestCase2() throws InterruptedException, Exception
{
logger.log(LogStatus.INFO, " Test Case2 Block Entered");
Thread.sleep(4000);
......
......
logger.log(LogStatus.INFO, "Assert Flag Received");
Thread.sleep(4000);
Assert.assertTrue(AssertFlag);
}
}
I am Using POM Classes along with TestNG and running the Testcases using testng.xml.
I am able to generate the Extent Report but unable to Differentiate Between TC1 & TC2 Logs i.e all test Case logs are getting appended to single TestCase as shown in the Above Screen Shot.
I want each Test Case Logs/Entry in separate rows in the Extent Reports.
Can Anyone please rectify the mistake in my code and help me out.
Thanks in Advance!!!
I think, you should initialize your logger in BeforeMethod and use report.flush() in AfterMethod. That may solve your problem.
Beginner in this space, appreciate your help on the problem!
I'm trying to script a path
Login
create new user
log out
Login method works fine
Create user is dependent on Login method to be completed, using data providers and post login to create new user
Issue is after logging in the elements/objects in create user class are not identified. I have tried it using different element finders and browsers. Appreciate if you help around
Project Structure is
Project
Package1
Logindataprovider.class
newaccountDataProvider.class
Package2
LoginpageObjects.class
NewAccountPageObjects.class
Package3
LoginTestscripts.class
NewAccountTestScript.class
LoginTestscripts- Class
LoginPageObjects LgnObj = new LoginPageObjects();
#Test(groups = { "Logingroup1" }, dataProvider = "LoginCred", dataProviderClass = LoginDataProviders.class)
public void mytest(String DDUname, String DDpwd,String ExpLoginPage, int Browsertype) {
LgnObj.setBrowser(Browsertype);
Logger log = Logger.getLogger(LoginDataProviders.class);
log.info("Login To application method");
LgnObj.init();
// Login page assertion actual values
String LoginPageAssertactual = LgnObj.LoginPageAssertionActual();
//Login page assertion
Assert.assertEquals(LoginPageAssertactual, ExpLoginPage);
//login to application
LogginCommonProcess(DDUname, DDpwd, LgnObj);
}
public void LogginCommonProcess(String DDUname, String DDpwd,
LoginPageObjects LgnObj) {
LgnObj.enterUserName(DDUname);
LgnObj.enterPassword(DDpwd);
LgnObj.Loginbtn();
LgnObj.enterPIN();
LgnObj.CompanyName();
}
Logindataprovider- Class
public class LoginPageObjects {
WebDriver driver;
public void setBrowser(int type) {
if (type == 1) {
driver = new FirefoxDriver();
} else if (type == 2) {
String path = ClassLoader.getSystemResource("chromedriver.exe")
.getPath();
System.setProperty("webdriver.chrome.driver", path);
driver = new ChromeDriver();
} else if (type == 3) {
String path = ClassLoader.getSystemResource("IEDriverServer.exe")
.getPath();
System.setProperty("webdriver.ie.driver", path);
driver = new InternetExplorerDriver();
}
}
public void init() {
driver.manage().window().maximize();
driver.navigate().to("https://test2.qatest.com/Login.aspx");
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
}
public String LoginPageAssertionActual() {
String LoginPageAssertionact = driver.findElement(By.tagName("h1"))
.getText();
return LoginPageAssertionact;
}
public void enterUserName(String DDUname) {
driver.findElement(By.id("ctl00_MainContent_usernameField")).sendKeys(
DDUname);
}
public void enterPassword(String DDpwd) {
driver.findElement(By.id("ctl00_MainContent_passwordField")).sendKeys(
DDpwd);
}
New User- page object
public class NewUser {
WebDriver driver;
public void setup() {
System.out.println("Start here");
System.setProperty("webdriver.ie.driver", "C:\\IEDriverServer.exe");
driver = new InternetExplorerDriver();
driver.manage().window().maximize();
driver.navigate().to("https://test2.directorsdesk.com/Login.aspx");
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
}
public void setBrowser(int type) {
if (type == 1) {
driver = new FirefoxDriver();
} else if (type == 2) {
String path = ClassLoader.getSystemResource("chromedriver.exe")
.getPath();
System.setProperty("webdriver.chrome.driver", path);
driver = new ChromeDriver();
} else if (type == 3) {
String path = ClassLoader.getSystemResource("IEDriverServer.exe")
.getPath();
System.setProperty("webdriver.ie.driver", path);
driver = new InternetExplorerDriver();
} else if (type == 4) {
DesiredCapabilities cap = DesiredCapabilities.chrome();
cap.setBrowserName("chrome");
cap.setVersion("38");
cap.setPlatform(Platform.WINDOWS);
try {
driver = new RemoteWebDriver(new URL(
"http://127.0.0.1:4444/wd/hub"), cap);
} catch (MalformedURLException e) {
// log erro unable to access remote system, running in local
// firefox
driver = new FirefoxDriver();
}
}
}
**public void ManageSystem() {
driver.findElement(By.partialLinkText("Manage System")).click();
driver.findElement(By.linkText("Manage System")).click();
}**
public class NewAccount {
#Test(dataProvider = "UserDetails", dataProviderClass = LoginDataProviders.class, dependsOnGroups = "Logingroup1")
public void CreateNewAccount(String Emailid, String Firstname,
String Lastname, String PrimaryEmailid, int browserType) {
NewUser NewUserObj = new NewUser();
NewUserObj.setBrowser(browserType);
**NewUserObj.ManageSystem();** // Fails here
NewUserObj.UserAccounts();
NewUserObj.NewUserAccount();
NewUserObj.Emailid(Emailid);
NewUserObj.UserFirstname(Firstname);
NewUserObj.UserLastname(Lastname);
NewUserObj.PrimaryEmai(PrimaryEmailid);
NewUserObj.SaveAccountSettings();
LoginPageObjects LgnPgObj = new LoginPageObjects();
LgnPgObj.Logout();
LgnPgObj.closeBrowser();
}
Have you tried this:
public void entityFieldIsEntered(String field, String value) {
WebElement valueElem = new SharedDriver().findElement(By.xpath("(.//*[text()='" + field
+ ":'])[2]/parent::*/span/input"));
valueElem.sendKeys(new CharSequence[] { value });
}
assuming you are using input wrapper in your html. This code search for text label on the screen, then goes to its parent and navigate to input field.
If you are going to use multiple page objects in one test, you will need to share the same driver between those page objects.
Try creating a separate setupDriver class and have each page object take a driver parameter to be constructed.
At the beginning of each test setup the driver, then pass in the driver as you create each object.
So I'm experimenting with Selenium automation, and I'm trying to write a testcase that logs in, goes to a specific page, inputs data, then presses submit. The issue is that when it runs, it types out the credentials, presses "Submit" the site returns:
This site uses HTTP cookies to verify authorization information.
Please enable HTTP cookies to continue.
But then when I added this line [denoted by //1]:
driver.findElement(By.cssSelector("p > input[type=\"submit\"]")).click();
It allowed the login to go through until it gets to the send message page [denoted by //2], it asks for credentials again (as if no login was ever made). So is firefox not accepting cookies at all? How do I fix this?
Source:
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.JUnitCore;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
public class LaPwn {
private WebDriver driver;
private String baseUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
private String UserID = "";
private String UserPW = "";
private String UserPIN = "";
public static void main(String[] args) throws Exception {
UserInfo User = new UserInfo();
User.setUserInfo();
System.out.println(User.getUserID());
System.out.println(User.getUserPW());
System.out.println(User.getUserPIN());
JUnitCore.main("LaPwn");
}
#Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = "https://my_url.com";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void testLaPwn() throws Exception {
driver.get(baseUrl + "/Login");
//1
driver.findElement(By.cssSelector("p > input[type=\"submit\"]")).click();
//1
driver.findElement(By.id("UserID")).clear();
driver.findElement(By.id("UserID")).sendKeys("User.getUserID()");
driver.findElement(By.name("PIN")).clear();
driver.findElement(By.name("PIN")).sendKeys("User.getUserPW()");
driver.findElement(By.cssSelector("p > input[type=\"submit\"]")).click();
driver.findElement(By.id("apin_id")).sendKeys("User.getUserPIN()");
driver.findElement(By.cssSelector("div.pagebodydiv > form > input[type=\"submit\"]")).click();
//2
driver.get(baseUrl + "/messagecenter");
//2
try {
assertEquals("Send message:", driver.getTitle());
} catch (Error e) {
verificationErrors.append(e.toString());
}
driver.findElement(By.id("user")).clear();
driver.findElement(By.id("user")).sendKeys("test123");
driver.findElement(By.id("messg")).clear();
driver.findElement(By.id("messg")).sendKeys("Hello test123!");
driver.findElement(By.xpath("(//input[#name='SEND_BTN'])[2]")).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;
}
}
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;
}
}
}
Based on your problem statement, the problem you are facing is that selenium is opening a fresh firefox profile where cookies are not enabled.
driver = new FirefoxDriver();
This is where you have to fix in such a way that it opens up a profile where cookies are enabled.
One way is to create your own profile in firefox and open that profile instead of directly opening by FirefoxDriver();
ProfilesIni profileObj = new ProfilesIni();
FirefoxProfile yourFFProfile = profileObj.getProfile("your profile");
driver = new FirefoxDriver(yourFFProfile);
This way you can do what ever setting you need to in that profile and run your tests under that settings. If enabling cookies is the need, do that in firefox options.
Following is another way to open a specific profile as per seleniumhq.org
File profileDir = new File("path/to/top/level/of/profile");
FirefoxProfile profile = new FirefoxProfile(profileDir);
profile.addAdditionalPreferences(extraPrefs);
WebDriver driver = new FirefoxDriver(profile);
Check the source for more info on this topic.
Source: http://docs.seleniumhq.org/docs/03_webdriver.jsp#modifying-the-firefox-profile
I actually realized I defined the base URL as
baseUrl = "https://my_url.com/";
and it was concatenating it like:
driver.get(baseUrl + "/Login");
for "https://my_url.com//Login". Thanks for your replay though!