Selenium-Java is opening two instances of Firefox - java

I'm just starting to learn selenium java.
I had this test code, its just basically open google.com page and get its title, and assert the title. my problem is every time I run the test, the Firefox gets called twice. I already search around about the possible issue, tried some of the fix. but nothing works for me.. tried changing "#BeforeTest" to "#BeforeClass" and to "#Before" still the same.
firefox version: 55.0.3
selenium version: 3.5.3
geckodriver : 0.19.0
here's my code:
public class ATest {
public String baseURL = "http://google.com";
public WebDriver driver;
#BeforeTest
public void setBaseURL() {
driver = new FirefoxDriver();
driver.get(baseURL);
}
#Test
public void verifyHomePageTitle() {
setBaseURL();
String expectedTitle = "Google";
String actualTitle = driver.getTitle();
Assert.assertEquals(actualTitle, expectedTitle);
}
}

#BeforeTest executes before tests so You need to remove setBaseURL() from Your test. It will be run before it anyway.

I haven't used Selenium with Java, only with Ruby. But my guess is that #BeforeTest directive makes setBaseURL() to be executed before each test. So here you have your first opened browser. Later when in your actual test what you do is you run setBaseURL() again, which opens second browser.
Remove setBaseURL() from verifyHomePageTitle(), or remove #BeforeTest

get method is called twice hence it loads page twice. Once in #BeforeTest and second in #Test by calling setBaseURL. Remove the setBaseURL from #BeforeTest, move the get method in actual #Test method and you should be fine
Here is what java doc says about get method
void get(java.lang.String url)
Load a new web page in the current browser window.
get
void get(java.lang.String url)
Load a new web page in the current browser window. This is done using an HTTP GET operation, and the method will block until the load is complete. This will follow redirects issued either by the server or as a meta-redirect from within the returned HTML. Should a meta-redirect "rest" for any duration of time, it is best to wait until this timeout is over, since should the underlying page change whilst your test is executing the results of future calls against this interface will be against the freshly loaded page. Synonym for WebDriver.Navigation.to(String).
Parameters: url - The URL to load. It is best to use a fully qualified URL
public class ATest {
public String baseURL = "http://google.com";
public WebDriver driver;
#BeforeTest
public void setBaseURL() {
driver = new FirefoxDriver();
}
#Test
public void verifyHomePageTitle() {
driver.get(baseURL);
String expectedTitle = "Google";
String actualTitle = driver.getTitle();
Assert.assertEquals(actualTitle, expectedTitle);
}
}
Links for reference
Java Doc : http://seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/WebDriver.html#get-java.lang.String-

Related

Not able to locate an element within the IFrame (Selenium)

So i have create successful test of adding a card to my profile and now i would like ot verify if card was added so i would like to check if "Your card was successfully added" text appeared, however for some kind of a reason the className not located.
This is an iframe however i do enter it to add the card details and submit them, so trying to understand why it cant locate the follow:
Adding card
public void addCard(Card card) {
switchToCardIframe()
.fillInCardNumber(card.getCardNumber())
.fillInCardHolder(card.getCardHolderName())
.fillInExpiryDate(card.getExpiryDate())
.fillInCvv(card.getCvv())
.clickOnToggle()
.clickOnAddButton();
}
This is how i locate the text
#FindBy(css = "payment-state-message")
private WebElement cardAddedIndicator;
Test
#Test
public void shouldSuccessfullyAddCard() {
myCards.addCard(cardData());
assertTrue(myCards.getCardAddedIndicator().isDisplayed());
}
I have also tried to check if another element displayed by escaping the iframe but no luck so any help appreciated
driver.switchTo().defaultContent()
I have also attempted Thread.sleep() for 10 seconds before taking getting the text from the css locater but not luck
Here is the base page where wait initialized
public class BasePage {
public WebDriver driver;
protected Wait wait;
public BasePage(WebDriver driver) {
initializePage(driver);
this.wait = new Wait(driver);
}
final protected void initializePage(WebDriver driver) {
this.driver = driver;
PageFactory.initElements(new AjaxElementLocatorFactory(driver, 20), this);
}
}
Your css is wrong, so instead of
#FindBy(css = "payment-state-message")
private WebElement cardAddedIndicator;
try this
#FindBy(css = ".payment-state-message")
private WebElement cardAddedIndicator;
also do not check for visibility by .isDisplay
rather have a text method called on it. Put some delay/wait as well.
String actualMessage = myCards.getCardAddedIndicator().getText();
String expectedMessage = "Your card was successfully added"
then assert these two based on their actual and expected behavior .
Conclusion :
When there is an iframe form and you submit it, it does not mean that its still the same iframe. In my case when I submitted the form then iframe disappeared however in order for for the element to be located I had to perform driver().switch().parentFrame()
FYI: First always check your locators and make sure they are right.

How do I close() and quit() Selenium driver without affecting other steps in Cucumber and Selenium?

I have two feature files in Cucumber that are linked to corresponding step files. The problem is that when one of the step file finishes execution then it closes all the browser windows (because of driver.quit()) whereby killing the execution of other step file which hasn't done processing yet.
Here each step file opens a new browser window, executes the tests within it and then closes and quits the browser. Currently I have just two step files but in the future there are going to be many more.
Is there anything in Cucumber that would always get executed after all the steps are executed?
How do I solve this problem?
HelpStep.java
#Ignore
public class HelpStep {
private WebDriver driver;
#Before
public void setup() {
System.out.println("Into the setup method of HelpStep...");
this.driver = BrowserConfig.getIEWebDriver();
}
#Given("^The user is on the Help page$")
public void onPage() {
System.out.println("The user is on the Help page");
}
#When("^The user clicks on the links within the Help page$")
public void clickLinks() {
System.out.println("The user clicks on the links within the Help page");
}
#Then("^The user is navigated to that section$")
public void validate() {
System.out.println("The user is navigated to that section");
}
#After
public void cleanUp() {
System.out.println("Into the cleanUp method of HelpStep...");
//FOLLOWING METHOD CALL KILLS ALL THE OPEN BROWSERS ALSO :(
BrowserConfig.releaseResources(this.driver);
}
}
LinkStatsStep.java
#Ignore
public class LinkStatsStep {
private WebDriver driver;
#Before
public void setup() {
System.out.println("Into the setup method of LinkStatsStep...");
this.driver = BrowserConfig.getIEWebDriver();
}
#Given("^The user is on the Link Statistics page$")
public void onPage() {
System.out.println("The user is on the Link Statistics page");
}
#When("^The user does a search$")
public void clickLinks() {
System.out.println("The user does a search");
}
#Then("^The user is displayed search result$")
public void validate() {
System.out.println("The user is displayed search result");
}
#After
public void cleanUp() {
System.out.println("Into the cleanUp method of LinkStatsStep...");
BrowserConfig.releaseResources(this.driver);
}
}
TestRunner.java
#RunWith(Cucumber.class)
#CucumberOptions(
plugin = {"pretty", "json:target/cucumber-reports/cucumber.json"},
features = {"src/test/resources/features"})
public class TestRunner extends ApplicationTests {
}
BrowserConfig.java
public class BrowserConfig {
private static final String IE_DRIVER_EXE = "drivers/IEDriverServer.exe";
private static final String WEBDRIVER_IE_DRIVER = "webdriver.ie.driver";
private static final String BASE_URL = "https://www.google.com";
public static WebDriver getIEWebDriver() {
String filePath = ClassLoader.getSystemClassLoader().getResource(IE_DRIVER_EXE).getFile();
System.setProperty(WEBDRIVER_IE_DRIVER, filePath);
InternetExplorerOptions options = new InternetExplorerOptions().requireWindowFocus();
options.setCapability(INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
options.setCapability(ENABLE_ELEMENT_CACHE_CLEANUP, true);
options.setCapability(IE_ENSURE_CLEAN_SESSION, true);
options.setCapability(ACCEPT_SSL_CERTS, true);
options.setCapability("nativeEvents", false);
options.setCapability(INITIAL_BROWSER_URL, BASE_URL);
System.out.println("Initializing IE Driver now...........");
WebDriver driver = new InternetExplorerDriver(options);
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
return driver;
}
public static void releaseResources(WebDriver driver) {
System.out.println("Releasing resources now.....");
if (null != driver) {
driver.close();
driver.quit(); //CLOSES ALL THE OPEN BROWSER SESSIONS LEAVING OTHER STEP EXECUTIONS INCOMPLETE
}
}
}
help.feature
Feature: Check that the user is able to navigate to Help page
Scenario:
Given The user is on the Help page
When The user clicks on the links within the Help page
Then The user is navigated to that section
link-stats.feature
Feature: Check that the user is able to navigate to Link Statistics page
Scenario:
Given The user is on the Link Statistics page
When The user does a search
Then The user is displayed search result
System.outs
Initializing IE Driver now...........
Listening on port 47613
Into the setup method of LinkStatsStep...
Initializing IE Driver now...........
Listening on port 5009
The user is on the Help page
The user clicks on the links within the Help page
The user is navigated to that section
Into the cleanUp method of HelpStep...
Releasing resources now.....
Into the cleanUp method of LinkStatsStep...
Releasing resources now.....
Into the setup method of HelpStep...
Initializing IE Driver now...........
Listening on port 17291
Into the setup method of LinkStatsStep...
Initializing IE Driver now...........
Listening on port 23793
The user is on the Link Statistics page
The user does a search
The user is displayed search result
Into the cleanUp method of HelpStep...
Releasing resources now.....
Into the cleanUp method of LinkStatsStep...
Releasing resources now.....
Looking at your code it would appear to be correct.
Calling quit should close all open windows associated with that webdriver session. It should not close windows of other webdriver sessions. So I think you are facing a problem in the IEDriverServer.
If this is the case and if you are running your tests in a JVM that shuts down after all tests have been executed. Then as a work around you can use shut down hooks to call quite and close all web driver sessions. For example:
private static final Thread CLOSE_THREAD = new Thread() {
#Override
public void run() {
// Start a new webdriver to call quit on
// For IE this will terminate all webdriver sessions
getIEWebDriver().quit();
}
};
static {
Runtime.getRuntime().addShutdownHook(CLOSE_THREAD);
}
Posted the answer here as this question is more or less similar earlier one.
https://stackoverflow.com/a/55836832/2325154
It is because driver management not done properly. I would suggest to use qaf which does driver and resource management. With QAF your step file will look like below:
public class HelpStep {
//setup or tear-down not required here...
#Given("^The user is on the Help page$")
public void onPage() {
//you can access driver any where like below:
//WebDriver driver = new WebDriverTestBase().getDriver();
System.out.println("The user is on the Help page");
}
#When("^The user clicks on the links within the Help page$")
public void clickLinks() {
System.out.println("The user clicks on the links within the Help page");
}
#Then("^The user is navigated to that section$")
public void validate() {
System.out.println("The user is navigated to that section");
}
}
To access driver object any where in the code you can get it from test base.
WebDriver driver = new WebDriverTestBase().getDriver();
Below are examples of interacting with element anywhere in the code:
Using findBy
driver.findElement("name=q").click();
Using element factory
import static com.qmetry.qaf.automation.ui.webdriver.ElementFactory.$;
...
$("name=q").click();
Using inbuilt step library
import static com.qmetry.qaf.automation.step.CommonStep.*;
...
click("name=q");
in example above name=q is element locator using name as locator strategy, which will automatically converted to By.name.
LinkStatsStep
import static com.qmetry.qaf.automation.step.CommonStep.*;
...
public class LinkStatsStep {
#Given("^The user is on the Link Statistics page$")
public void onPage() {
get("/");
}
#When("^The user does a search$")
public void clickLinks() {
System.out.println("The user does a search");
click("elementlocator");
//$("elementlocator").click();
}
#Then("^The user is displayed search result$")
public void validate() {
verifyLinkWithPartialTextPresent("link text");
//$("partialLink=link text").verifyPresent();
}
}
Your gherkin file will remain same. To run your gherkin file use GherkinScenarioFactory
You can specify browser to use using driver.name property. You don't need to write code for creating or tearing down driver. You can set behavior of driver session by using selenium.singletone property.
#this will tear down driver after each testcase/scenario
selenium.singletone=method
#this will tear down driver after each xml test node in configuration file
selenium.singletone=test
#this will tear down driver after each xml test node in configuration file and will reuse same driver session for testcases/scenario configured under same xml test node.
selenium.singletone=test
#this will tear down driver after each xml suite node in configuration file.
selenium.singletone=suite

JAVA - Selenium WebDriver - Assertions and Waits

I am having a problem with my Assertion, or rather with the "time" the assertion is being executed. So, the assertion is working as it should, however, it is going too fast, as it is executing without waiting for the page it should be targeting to load. Which means that the assertion is failing the test.
Having this in mind, I tried searching around how to add a "wait" to the assert to make it wait for the page to load before running, but with no success.
So, would anyone, please be able to help with this, as in how would I code so, that the assert "waits" for the page to load and then executes?
I've tried adding the wait to the header method, i tried adding the wait to the test script, but no success.
public class test1 extends DriverSetup{
//Here we are setting the method to use the homePage
private HomePage homePage = new HomePage(getDriver());
//Here we are setting the method logInPage
private AuthenticationPage authenticationPage = new AuthenticationPage(getDriver());
//Here are setting the method CreateAccountPage
private CreateAccountPage createAccountPage = new CreateAccountPage(getDriver());
//Here we are setting the method to access the Website HomePage with the driver
private void accessWebsiteHomePage (){
getDriver().get("http://automationpractice.com/index.php");
}
#Test
public void CreateAccount() {
accessWebsiteHomePage();
//Log in
homePage.logInBut();
//Authentication page "Create a new account" box
authenticationPage.setCreateAccountEmailAddress(emailGenerator.Email());
authenticationPage.CreateAccountButtonClick();
Assert.assertEquals("CREATE AN ACCOUNT", createAccountPage.HeaderCheckRightPage());
The assert should be targeting the "CREATE AN ACCOUNT" page, but it is targeting the "AUTHENTICATION" page, which comes before it, hence the test fails as the "actual" value being printed is the "AUTHENTICATION" page, not the "CREATE AN ACCOUNT" page.
You need to use an explicit wait. Here is one that will wait for the title to be equal to something:
private ExpectedCondition<Boolean> titleIsEqualTo(final String searchString) {
return driver -> driver.getTitle().equals(searchString);
}
You can make it more reliable by forcing the case of what you want to match like this:
private ExpectedCondition<Boolean> titleIsEqualTo(final String searchString) {
return driver -> driver.getTitle().toLowerCase().equals(searchString.toLowerCase());
}
You would then need to put the following in before your assertion:
WebDriverWait wait = new WebDriverWait(driver, 10, 100);
wait.until(titleIsEqualTo("CREATE AN ACCOUNT"));
I'm making the assumption that by header you mean the page title since you haven't shown the code that collects the header.
*Edit*
A non-lambda version of the above ExpectedCondition is:
private ExpectedCondition<Boolean> titleIsEqualTo(final String searchString) {
return new ExpectedCondition<Boolean>() {
#Override
public Boolean apply(WebDriver driver) {
return driver.getTitle().toLowerCase().equals(searchString.toLowerCase());
}
};
}

Selenium Webdriver, Javascript link, Unable to locale Element

Hi I am facing this issue, Below is a code which i had generated using Selenium IDE, Basically i am trying to access a career portal of the particular website below and for the Jobposting QA specialist, I was experimenting to auto complete the application using Selenium.
1) I am not able to replicate the code working in webdriver despite adding the code under proper class and importing all the necessary packages.
2) On running it as a TestNG test, i have a failure showing Unable to find Element.
3) The link to the QA specialist is not being detected by the driver either if i give it as identify By.link text or By.xpath.
4) please guide me where i am making mistake.
5) I am a beginer to Selenium
public class Application {
private WebDriver driver;
private String baseUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
#Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = "http://www.saymedia.com/";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void testApplication() throws Exception {
driver.get(baseUrl + "/jobs");
driver.findElement(By.linkText("QA Specialist")).click();
driver.findElement(By.linkText("Apply Now")).click();
driver.findElement(By.linkText("Send Application")).click();
}
Your elements are inside of an iframe. Selenium only interacts with elements in the current frame. Any element within a child frame cannot be interacted with until you switch into that frame. You can switch by using switchTo().frame():
driver.get(baseUrl + "/jobs");
driver.switchTo().frame("jobviteframe");
driver.findElement(By.linkText("QA Specialist")).click();
driver.findElement(By.linkText("Apply Now")).click();
driver.findElement(By.linkText("Send Application")).click();
The arguments for frame() are
number from 0
id of the frame
the webelement rerference of the frame
When done in the iframe, use the following to exit back to the top of the document:
driver.switchTo().defaultContent();

How to verify a page title using WebDriver and page object?

I am trying to write a method to verify page title using page objects but I am unable to do it. Could you please help me out how to write a method to verify page title after searching something in the google page.
Here is my 2 classes.
Class 1
public class GoogleSearchPage {
protected WebDriver driver;
#FindBy(name="q")
private WebElement SearchBox;
#FindBy(name="btnG")
private WebElement SearchButton;
public void SearchFor(String SearchTerm)
{
SearchBox.sendKeys(SearchTerm);
SearchButton.click();
}
}
Class2
public class TestSearchResults {
WebDriver driver;
GoogleSearchPage page;
#BeforeClass
public void Launch() throws Exception
{
driver = new FirefoxDriver();
driver.get("http://google.com");
}
#AfterClass
public void Close()
{
driver.quit();
}
#Test
public void ResultPage() {
System.out.println(page);
page=PageFactory.initElements(driver, GoogleSearchPage.class);
page.SearchFor("selenium");
}
}
Could you please help how to verify the title after displaying the Search results
Note: I am using TestNG.
Thanks in Advance,
Shiva Oleti.
Try this:
assertEquals("Your Page Title" , driver.getTitle());
driver.getTitle() - Returns Title of your current page.
You can get & verify title of page using python webdriver. See below codes
driver.title('title name')
assert 'title name' in driver.title('title name')
It will verify the title name. if it is there title name test case pass else through assert error.
Create a constructor in each page object. The constructor:
sets the instance driver value
waits for page load to complete (e.g. loading spinner not visible, jQuery.active == 0, document.readyState == 'complete')
verifies the page title (see other answers)
Issue PageFactory.initElement(driver, this);
Therefore you don't need a separate method to verify title. In each step you will have a new YourPageObjectPage() which checks the title automatically. Think DRY.

Categories

Resources