GEB :One class Test cases are not opening in separate browser - selenium

I imported an old project from that has a class named "TestGebSpec". The test cases of it were running on the same browser so I added a "CachingDriverFactory.clearCacheAndQuitDriver()" to gebConfig.groovy file. Still, test cases were running on the same browser so I create a new groovy test case file "Login TC"
Now the problem is the test case of Login TC are running on a separate browser i.e for each test case a new driver is initiated but for file "TestGebSpec" somehow TC runs on the same browser
Any suggestions???
Code of "TestGebSpec" file
#Stepwise
#SuppressWarnings(["GrUnresolvedAccess", "GroovyAssignabilityCheck", "UnnecessaryQualifiedReference"])
class KohlerSanityTestGebSpec extends GebReportingSpec {
public static final String USER_EMAIL = "test_user." + UUID.randomUUID() + "#kohler.com"
public static final String USER_PASSWORD = "pass123Word"
#Shared
productAddedToFolder
def setupSpec() {
driver.manage().window().maximize()
}
def setup() {}
def cleanup() {}
def cleanupSpec() {}
//--------------------------------------------------------------
// Utility methods start here.
//--------------------------------------------------------------
/** Using javascript runner to scroll an element into view so selenium can work with it. */
protected void scrollIntoViewJS(NonEmptyNavigator element) {
((JavascriptExecutor) driver).executeScript(
"arguments[0].scrollIntoView(true);",
element.firstElement());
sleep(1000)
}
protected void scrollUp(int distance) {
((JavascriptExecutor) driver).executeScript("scroll( 0, ${-distance});");
sleep(100)
}
protected void scrollDown(int distance) {
((JavascriptExecutor) driver).executeScript("scroll( 0, ${distance});");
sleep(100)
}
protected void hoverTest2(NonEmptyNavigator element) {
((JavascriptExecutor) driver).executeScript(
"arguments[0].trigger(\"hover\");",
element.firstElement());
}
protected void hoverOver(String path) {
org.openqa.selenium.WebElement element =
driver.findElement(org.openqa.selenium.By.cssSelector(path))
hoverOver(element)
}
protected void hoverOver(NonEmptyNavigator element) {
org.openqa.selenium.interactions.Actions builder = new
org.openqa.selenium.interactions.Actions(driver)
builder.moveToElement(element.getElement(0)).build().perform()
}
/** click, when the click() method does not work. */
#SuppressWarnings("GroovyUnusedDeclaration")
protected void clickElement(NonEmptyNavigator element) {
org.openqa.selenium.interactions.Actions builder = new org.openqa.selenium.interactions.Actions(driver)
builder.moveToElement(element.getElement(0)).click().build().perform()
}
protected void moveElement(NonEmptyNavigator handleElement, NonEmptyNavigator trackElement, int xPercent) {
org.openqa.selenium.WebElement handle = handleElement.getElement(0)
org.openqa.selenium.WebElement track = trackElement.getElement(0)
org.openqa.selenium.interactions.Actions builder = new org.openqa.selenium.interactions.Actions(driver)
int width = track.getSize().getWidth()
int moveLength = width * xPercent / 100
builder.dragAndDropBy(handle as org.openqa.selenium.WebElement, moveLength.intValue(), (int) 0).build().perform()
}
protected void closeSurveyPopup() {
if ($("#IPEbgCover")) {
$("area", alt: "close").click()
}
}
//----------------------------------------------------------------
// End of utility methods. Start of feature methods.
//----------------------------------------------------------------
def "Create project in bCC TESTCASE1"() {
browser.baseUrl = "URL"
when: "I log in to the BCC"
to BccLoginPage
loginForm.login = "data"
loginForm.$("#loginPassword").value("data")
$("input", type: "submit").click()
then:
at BccHomePage
when:
newCaProjectButton.click()
then:
at BccNewCaProject01Page
when: "I name and describe the new project."
def newProjectName = "gebtest-" + randomString(16, ('A'..'Z') + ('0'..'9'))
println "Creating BCC project \"$newProjectName\"."
projectNameInput.value(newProjectName)
projectDescriptionInput.value(randomString(50))
createProcessButton.click()
then:
at BccCaProjectDetailsPage
}
}
code of "Login TC" file
class LoginTC extends GebReportingSpec{
def setupSpec() {
driver.manage().window().maximize()
//driver.manage().window().size = new org.openqa.selenium.Dimension( 1200, 1200 )
} // run before the first feature method
def setup() {} // run before every feature method
def cleanup() {} // run after every feature method
def cleanupSpec() {} // run after the last feature method
void "login tc2"(){
setup:
to HomePage
final String searchString = "string data"
searchInput = searchString
when:
btnSearch.click()
then:
at waitFor{ ProductDetailPage }
and:
sku.text().toLowerCase().contains( searchString.toLowerCase() )
}
void "login tc3"(){
setup:
to HomePage
final String searchString = "string data"
searchInput = searchString
when:
btnSearch.click()
then:
at waitFor{ ProductDetailPage }
}
}
In short problem is why features on "TestGebSpec" file runs on same browser
Flow is as below
1.Open browser
2.Feature 1 run
3.Feature 2 run
.
.
.
final point. Browser close
What I except
1.open browser
2.Feature 1 run
3.Close browser
4.Open browser
5.Feature 2 run
6.Close browser

Actually an error on your web page should not be a problem if the next feature opens the initial URL it needs afresh. Also cookies should not be a problem because you can delete them manually or automatically. Over-using #Stepwise is a source of problems for many users, too. You should avoid it whenever possible. I even see you use it in a specification with only one feature (or maybe you only showed me one and actually there are more). Using many browsers is a huge resource waste and just makes your tests slow. The Book of Geb (manual) is an excellent source of information.
Take a look at implicit lifecycle with regard to clearCookies() andclearWebStorage(). Auto-clearing cookies and/or web storage might also be helpful. The same chapter also explains that if you just use CachingDriverFactory.clearCacheAndQuitDriver() at the end of a feature method (or in cleanup() if you need it in every feature), the next method will get a new browser instance automatically.
Of course you can quit the browser via quit() (quits the browser) and close() (closes current browser window) if you want to start the new browser manually. But implicit driver management is easier to use IMO, so I am just mentioning it for completeness' sake.
Now for a very special case: You can even use something like resetBrowser(); CachingDriverFactory.clearCacheAndQuitDriver() in the middle of a single feature method like this:
package de.scrum_master.testing
import geb.driver.CachingDriverFactory
import geb.spock.GebReportingSpec
class RestartBrowserIT extends GebReportingSpec {
def "Search web site Scrum-Master.de"() {
when:_ "download page is opened"
go "https://scrum-master.de"
report "welcome page"
then:_ "expected text is found on page"
$("h2").text().startsWith("Herzlich Willkommen bei Scrum-Master.de")
when:_ "browser is reset"
resetBrowser()
CachingDriverFactory.clearCacheAndQuitDriver()
and:_ "download page is opened again in new browser"
go "https://scrum-master.de/Downloads"
report "download page"
then:_ "expected text is found on page"
$("h2").text().startsWith("Scrum on a Page")
}
}
Then on the console you see something like this:
download page is opened
07:49:49.105 [main] INFO i.g.bonigarcia.wdm.WebDriverManager - Using chromedriver 83.0.4103.39 (since Google Chrome 83 is installed in your machine)
07:49:49.146 [main] INFO i.g.bonigarcia.wdm.WebDriverManager - Exporting webdriver.chrome.driver as C:\Users\alexa\.m2\repository\webdriver\chromedriver\win32\83.0.4103.39\chromedriver.exe
Starting ChromeDriver 83.0.4103.39 (ccbf011cb2d2b19b506d844400483861342c20cd-refs/branch-heads/4103#{#416}) on port 3302
Only local connections are allowed.
Please see https://chromedriver.chromium.org/security-considerations for suggestions on keeping ChromeDriver safe.
ChromeDriver was started successfully.
Jul 03, 2020 7:49:53 AM org.openqa.selenium.remote.ProtocolHandshake createSession
INFORMATION: Detected dialect: W3C
expected text is found on page
browser is reset
download page is opened again in new browser
07:49:57.387 [main] INFO i.g.bonigarcia.wdm.WebDriverManager - Using chromedriver 83.0.4103.39 (since Google Chrome 83 is installed in your machine)
07:49:57.413 [main] INFO i.g.bonigarcia.wdm.WebDriverManager - Exporting webdriver.chrome.driver as C:\Users\alexa\.m2\repository\webdriver\chromedriver\win32\83.0.4103.39\chromedriver.exe
Starting ChromeDriver 83.0.4103.39 (ccbf011cb2d2b19b506d844400483861342c20cd-refs/branch-heads/4103#{#416}) on port 27426
Only local connections are allowed.
Please see https://chromedriver.chromium.org/security-considerations for suggestions on keeping ChromeDriver safe.
ChromeDriver was started successfully.
Jul 03, 2020 7:50:00 AM org.openqa.selenium.remote.ProtocolHandshake createSession
INFORMATION: Detected dialect: W3C
expected text is found on page
P.S.: Just in case you are wondering why I write when:_ "label" instead of just when: "label", I use this SpockConfig.groovy file in order to help me print labels in my test, as you can also see in the console log above:
import spock.lang.Specification
/**
* Use like this in order to print Spock/Geb labels:
* given:_ "foo"
* when:_ "bar"
* then:_ "zot"
*/
class LabelPrinter {
def _(def message) {
println message
true
}
}
Specification.mixin LabelPrinter
The Spock configuration file should be in src/main/resources/SpockConfig.groovy if you use a standard Maven directory layout.

Related

How to Take Screenshot when TestNG Assert fails?

String Actualvalue= d.findElement(By.xpath("//[#id=\"wrapper\"]/main/div[2]/div/div[1]/div/div[1]/div[2]/div/table/tbody/tr[1]/td[1]/a")).getText();
Assert.assertEquals(Actualvalue, "jumlga");
captureScreen(d, "Fail");
The assert should not be put before your capture screen. Because it will immediately shutdown the test process so your code
captureScreen(d, "Fail");
will be not reachable
This is how i usually do:
boolean result = false;
try {
// do stuff here
result = true;
} catch(Exception_class_Name ex) {
// code to handle error and capture screen shot
captureScreen(d, "Fail");
}
# then using assert
Assert.assertEquals(result, true);
1.
A good solution will be is to use a report framework like allure-reports.
Read here:allure-reports
2.
We don't our tests to be ugly by adding try catch in every test so we will use Listeners which are using an annotations system to "Listen" to our tests and act accordingly.
Example:
public class listeners extends commonOps implements ITestListener {
public void onTestFailure(ITestResult iTestResult) {
System.out.println("------------------ Starting Test: " + iTestResult.getName() + " Failed ------------------");
if (platform.equalsIgnoreCase("web"))
saveScreenshot();
}
}
Please note I only used the relevant method to your question and I suggest you read here:
TestNG Listeners
Now we will want to take a screenshot built in method by allure-reports every time a test fails so will add this method inside our listeners class
Example:
#Attachment(value = "Page Screen-Shot", type = "image/png")
public byte[] saveScreenshot(){
return ((TakesScreenshot)driver).getScreenshotAs(OutputType.BYTES);
}
Test example
#Listeners(listeners.class)
public class myTest extends commonOps {
#Test(description = "Test01: Add numbers and verify")
#Description("Test Description: Using Allure reports annotations")
public void test01_myFirstTest(){
Assert.assertEquals(result, true)
}
}
Note we're using at the beginning of the class an annotation of #Listeners(listeners.class) which allows our listeners to listen to our test, please mind the (listeners.class) can be any class you named your listeners.
The #Description is related to allure-reports and as the code snip suggests you can add additional info about the test.
Finally, our Assert.assertEquals(result, true) will take a screen shot in case the assertion fails because we enabled our listener.class to it.

After trying all solutions still facing - system.property org.testng.TestNGException: Cannot instantiate class

I am getting above error (org.testng.TestNGException: Cannot instantiate class) while running my first TestNG program. I have already gone through all the solutions but still issue persists.
I have already downloaded ChromeDriver, set it's correct path in class by using syste.property. Added required jars also. I have set system.setproprty() for chrome Driver, still gettimg the same error. Do I need to add any specific dependency in pom.xml or need to add main() in class?
Below is my class: My question is not getting posted due to less content explanation even thouguh I have written a lot, so adding this also. Parden me for this.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.Test;
/**
* Unit test for simple App.
*/
public class AppTest {
/**
* Create the test case
*
* #param testName
* name of the test case
*/
public AppTest(String testName) {
super();
System.setProperty("webdriver.chrome.driver", "C:/Users/Dell/Downloads/chromedriver_win32/chromedriver.exe");
}
// public static void main()
// {
//
// }
public WebDriver driver = new ChromeDriver();
String appUrl = "https://google.com";
#Test
public void gmailLogin() {
// launch the fire fox browser and open the application url
driver.get(appUrl);
System.out.println("Suceessfully opened the browser URL");
// maximize the browser window
driver.manage().window().maximize();
// declare and initialize the variable to store the expected title of
// the web page.
String expectedTitle = "Sign in - Google Accounts";
// fetch the title of the web page and save it into a string variable
String actualTitle = driver.getTitle();
Assert.assertEquals(expectedTitle, actualTitle);
// enter a valid user name in the email text box
WebElement username = driver.findElement(By.id("Email"));
username.clear();
username.sendKeys("TestSelenium");
// enter a valid password in the password text box
WebElement password = driver.findElement(By.id("Passwd"));
password.clear();
password.sendKeys("password123");
// click on the Sign in button
WebElement SignInButton = driver.findElement(By.id("signIn"));
SignInButton.click();
// close the web browser
driver.close();
}
}
Below are the error logs: I have set System.setProperty() for chrome Driver, still getting the same error. Do I need to add any specific dependency in pom.xml or need to add main() in class?
[RemoteTestNG] detected TestNG version 6.14.2
org.testng.TestNGException:
Cannot instantiate class com.selenium.SampleDemo1.AppTest
at org.testng.internal.ObjectFactoryImpl.newInstance(ObjectFactoryImpl.java:30)
at org.testng.internal.ClassHelper.createInstance1(ClassHelper.java:423)
at org.testng.internal.ClassHelper.createInstance(ClassHelper.java:336)
at org.testng.internal.ClassImpl.getDefaultInstance(ClassImpl.java:125)
at org.testng.internal.ClassImpl.getInstances(ClassImpl.java:190)
at org.testng.TestClass.getInstances(TestClass.java:95)
at org.testng.TestClass.initTestClassesAndInstances(TestClass.java:81)
at org.testng.TestClass.init(TestClass.java:73)
at org.testng.TestClass.<init>(TestClass.java:38)
at org.testng.TestRunner.initMethods(TestRunner.java:389)
at org.testng.TestRunner.init(TestRunner.java:271)
at org.testng.TestRunner.init(TestRunner.java:241)
at org.testng.TestRunner.<init>(TestRunner.java:192)
at org.testng.remote.support.RemoteTestNG6_12$1.newTestRunner(RemoteTestNG6_12.java:33)
at org.testng.remote.support.RemoteTestNG6_12$DelegatingTestRunnerFactory.newTestRunner(RemoteTestNG6_12.java:66)
at org.testng.SuiteRunner$ProxyTestRunnerFactory.newTestRunner(SuiteRunner.java:713)
at org.testng.SuiteRunner.init(SuiteRunner.java:260)
at org.testng.TestNG.run(TestNG.java:1017)
at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:114)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at org.testng.internal.ObjectFactoryImpl.newInstance(ObjectFactoryImpl.java:24)
... 25 more
Caused by: java.lang.IllegalStateException: The path to the driver executable must be set by the webdriver.chrome.driver system property; for more information, see https://github.com/SeleniumHQ/selenium/wiki/ChromeDriver. The latest version can be downloaded from http://chromedriver.storage.googleapis.com/index.html
I have set system.setproprty() for chrome Driver, still gettimg the same error. Do I need to add any specific dependency in pom.xml or need to add main() in class?I have set system.setproprty() for chrome Driver, still gettimg the same error. Do I need to add any specific dependency in pom.xml or need to add main() in class?
The AppTest constructor method where you are setting the system property for chrome driver is not being invoked during execution as per the current code. You can add a new setUpAppTest method with #BeforeClass annotation, so that, the system property can be set for chrome before initializing the chrome driver, as shown below:
#BeforeClass
public void setUpAppTest(String testName) {
System.setProperty("webdriver.chrome.driver", "C:/Users/Dell/Downloads/chromedriver_win32/chromedriver.exe");
}
You will have to import org.testng.annotations.BeforeClass in order to use BeforeClass. Additionally, I would suggest you to use driver.quit(); instead of driver.close(); to ensure proper clean-up of webdriver instance.
I see few issues with the way above method is implemented. Above code is more of the sequential flow where you are defining the initialization in later part of the code, hence you are seeing the above exception.
Try to have a superclass where initialization of the drivers, system property are required to run the test cases. For example: (Define a driver class like below)
public class OnUIStart{
protected void starting(Description description) {
super.starting(description);
if (!DriverManager.INSTANCE.getDriver().isDriverStarted()) {
String testBrowser = System.getenv("TEST_BROWSER");
BrowserType browserType;
if (!StringUtils.isBlank(testBrowser)) {
browserType = BrowserType.valueOf(testBrowser.toUpperCase());
} else {
browserType = BrowserType.CHROME;
}
DriverManager.INSTANCE.setDriverConfiguration(getDriverConfiguration(browserType));
DriverManager.INSTANCE.startDriver();
String url = LocalConfig.INSTANCE.getUrlWithProtocol();
ChangeResolution.setDesktop();
log.info("URL: " + url);
DriverManager.INSTANCE.get(url);
}
}
}
With the above code you can set all the system properties and initialization required. Make sure you have proper modularization of the methods which you defining.
In your test case
public class testClass extends OnUIStart {
}
Above implementation make sure all the initialization happening properly.

Browser Restart Using Geb & Spock within same test

I would like to be able to restart my browser session mid test using Geb and Spock Framework. I no howto close the browser and update after test compltion etc, but when i close during the test and try and re use the browser object i get a session error thrown by selenium. Below is the base outline i am trying to execute. NB never allows me to navigate to the new StoreHome and if i try and use just Browser i get error thrown.
#Category(High.class)
def "TC1: Verify Browser Restart"() {
when: "On my StoreFront HP wait until title displayed"
to StoreHomePage
waitFor { homepagetitle.displayed }
then: "Update your site picker"
mySitePicker.click()
waitFor { myNewHomePageTitle.displayed }
when: "Close the browser and insure on restart new page is loaded"
browser.close()
browser.quit()
def nb = new Browser()
nb.to(NewStoreHomePage)
then: "Validate on New HP"
asset myNewHomePageTitle.displayed
}
It's as simple as doing the following in your spec:
resetBrowser()
CachingDriverFactory.clearCacheAndQuitDriver()
After that any code that tries to access browser will trigger automatic creation of new WebDriver and Browser instances.
This is how you force a new driver:
CachingDriverFactory.clearCache()
I tested it, it works beautifully. This hint can also be found in the Geb manual.
Update 2017-02-07 15:10 CET: Thanks for the follow-up question. Well, my brief answer was made under the assumption that the command is issued at the end of one feature method and the next feature method starts with a new browser session. In order to do this mid-test you would have to create a new WebDriver instance manually and somehow trick Geb into updating its browser session.
Because this is tricky at least and I do not know how to do it, I recommend using two separate feature methods for testing what should be tested before and after quitting the browser. You can share state between them via #Shared members, if necessary. This also had the advantage that if you let Geb create the new WebDriver and browser session for you, everything configured in GebConfig.groovy, such as browser type and capabilities, will automatically be considered. If you would create a driver manually, you would have to parse the Geb config by yourself - ugly!
But the main problem with this approach is: How to assure that the feature methods are executed in the (lexical) order of declaration? Normally tests should be runnable in any order, so you cannot and should not rely on a specific execution order. Spock offers the Stepwise annotation to adress the rare case in which you want to enforce execution order, but this would lead to the same problem as in the mid-test situation because Geb implicitly assumes that it should continue to test in the same session. I.e. we need a trick to enforce lexical execution order without using #Stepwise.
Another problem is that if your spec extends GebReportingSpec because you want to take screenshots, Geb fails to take the last screenshot at the end of the feature method with the browser gone. Now you can configure Geb not to take screenshots if the test succeeds via reportOnTestFailureOnly, but that still leaves us with failed tests. So I added an override for the report method with some additional exception handling.
The full solution looks like this, derived from one of my real-life tests:
package de.scrum_master.tdd
import geb.driver.CachingDriverFactory
import geb.spock.GebReportingSpec
import org.openqa.selenium.Keys
import org.spockframework.runtime.model.FeatureInfo
import spock.lang.Shared
class SampleGebIT extends GebReportingSpec {
#Override
void report(String label = "") {
// GebReportingSpec tries to write a report (screenshot) at the end of each feature
// method. But because we use 'CachingDriverFactory.clearCacheAndQuitDriver()',
// there is no valid driver instance anymore from which to get a screenshot. Geb is
// unprepared for this kind of error, so we handle it gracefully so as to keep the
// test from failing just because the last screenshot cannot be taken anymore.
try {
super.report(label)
}
catch (Exception e) {
System.err.println("Cannot create screenshot: ${e.message}")
}
}
// We cannot use 'specificationContext' directly from 'setupSpec()' because of this
// compilation error: "Only #Shared and static fields may be accessed from here"
// Okay then, so use we a #Shared field as a workaround. ;-)
#Shared
def currentSpec = specificationContext.currentSpec
def setupSpec() {
// Make sure that feature methods are run in declaration order. Normally we could
// use #Stepwise for this, but because #Stepwise implies staying in the same
// browser session, it would not work in connection with
// 'CachingDriverFactory.clearCacheAndQuitDriver()'. This is the workaround for it.
for (FeatureInfo feature : currentSpec.features)
feature.executionOrder = feature.declarationOrder
}
def "Search web site Scrum-Master.de"() {
setup:
def deactivateAutoComplete =
"document.getElementById('mod_search_searchword')" +
".setAttribute('autocomplete', 'off')"
def regexNumberOfMatches = /Insgesamt wurden ([0-9]+) Ergebnisse gefunden/
when:
go "https://scrum-master.de"
report "welcome page"
then:
$("h2").text().startsWith("Herzlich Willkommen bei Scrum-Master.de")
when:
js.exec(deactivateAutoComplete)
$("form").searchword = "Product Owner" + Keys.ENTER
then:
waitFor { $("form#searchForm") }
when:
report "search results"
def searchResultSummary = $("form#searchForm").$("table.searchintro").text()
def numberOfMatches = (searchResultSummary =~ regexNumberOfMatches)[0][1] as int
then:
numberOfMatches > 0
cleanup:
println "Closing browser and WebDriver"
CachingDriverFactory.clearCacheAndQuitDriver()
}
def "Visit Scrum-Master.de download page"() {
when:
go "https://scrum-master.de/Downloads"
report "download page"
then:
$("h2").text().startsWith("Scrum on a Page")
}
}
BTW, I tested this successfully with several browsers on my Windows 10 machine:
HtmlUnit (with activated JavaScript)
PhantomJS
Chrome
Internet Explorer
Edge
Firefox

Intellij 13 ultimate runs geb tests smoothly but they wait when run independently

I am using cucumber groovy with geb.
Here is my profile and driver
FirefoxProfile firefoxProfile = new FirefoxProfile();
firefoxProfile.setAcceptUntrustedCertificates(true);
firefoxProfile.setAssumeUntrustedCertificateIssuer(false);
firefoxProfile.setPreference("browser.helperApps.neverAsk.saveToDisk",
"text/csv,application/pdf,application/csv,application/vnd.ms-excel");
firefoxProfile.setPreference("browser.download.manager.showAlertOnComplete",false);
firefoxProfile.setPreference("browser.download.manager.showWhenStarting", false);
firefoxProfile.setPreference("browser.download.manager.useWindow", false);
firefoxProfile.setPreference("browser.helperApps.deleteTempFileOnExit", true);
firefoxProfile.setPreference("webdriver.load.strategy", "unstable")
driver = {
def driver = new FirefoxDriver(firefoxProfile)
driver
}
Here is my step definition (FYI, this is the firstmost step)
MyPage.setUrl(Globals.get(key))
to MyPage
waitFor(10,0) {
ExpectedConditions.presenceOfElementLocated(By.tagName("title"))
}
at MyPage
I noticed that if i put a breakpoint at "at MyPage" in intellij and debug then it breaks at that point and then i can resume. However if I simply run either from Intellij or using ./gradlew clean cucumber
then the page loads and waits for a long time. I don't think it ever proceeds (only waited for a minute to check)
Whats the issue here ?
Update 1
class MyPage extends Page{
static url = ""
static at = {
module1.attrib.value() != null
Globals.get(module1.attrib.value())
}
static content = {
module1 { module Module1 } // Simple Geb Module
module2 { fieldsMap -> module Module2, fieldsMap: fieldsMap }
}
}
class Module2 extends Module {
def fieldsMap
static content = {
textField { $("input", name: fieldsMap['textFieldName']) }
}
}
Try doing it in a more gebish way:
Set the url explicitly in a subClass of MyPage - you should really try to use one page object per page.
define an at condition and use it to test for the waitFor condition for the page to wait till its loaded.
By default an at condition will wait for its condition to be true.
and
do not use ExpectedConditions try something more Gebish like:
waitFor { title != "" }
In your at condition you have not properly specified a truth statement. Although I am not sure what Globals.get(module1.attrib.value()) returns? But it looks like you should remove this line and do this logic somewhere else.
Calling value returns a string.
Module 1
class MyPage extends Page{
static url = ""
static at = {
waitFor { module1.attrib.value() != "" }
}
}
MyPage.setUrl(Globals.get(key))
to MyPage
at MyPage
Just nit picking here:
driver = {
new FirefoxDriver(firefoxProfile)
}
Updated version of Selenium and firefox fixed the issue.
Closing this

Is it possible to start few seleniums for one selenium server?

Is this valid code?
selenium = new DefaultSelenium("localhost", 4444, "*iehta",
"http://www.google.com/");
selenium.start();
...
selenium.stop();
...
selenium.start();
...
selenium.stop();
There's nothing wrong with having multiple browsers open (what you call "seleniums"). In fact, it's the only way you can test certain applications. Imagine an application that has an administrative UI and an end-user UI, where you make changes on the admin side and verify their effects on the user side. You can either write your test to jump back and forth between the two on the same browser session, or you can open two browsers, one for each aspect of the application. The former is the usual technique, but the latter is much cleaner.
And why do you think it shouldn't be safe? unless it works ok it's fine, If it doesn't than recreate the DefaultSelenium object again, it won't slow down your code anyway
You should usually keep start() and stop() as you set up and tear down methods. While using TestNG you can annonate then with #BeforeClass and #AfterClass annonations. Hence browser would be launched and shut down only before and after a test method in a class.
b/w did you support Selenium Proposal on area51 - http://area51.stackexchange.com/proposals/4693/selenium
This proposal is backed by SeleniumHQ and we need more users to commit to it to make it see day of light.
That was my fault.
Unexpected behaviour caused by this code and occurs because I stop selenium two times (selenium object never become null):
public class SeleniumController {
private static Selenium selenium;
public static Selenium startNewSelenium(){
// if already exists stop it and replace with new one
if(selenium != null){
selenium.stop();
}
selenium = createNewSelenium(getCurContext());
return selenium;
}
public static void stopSelenium() {
if(selenium != null){
selenium.stop();
}
}
private static Selenium createNewSelenium(TestContext testContext){
TestProperties testProps = new TestProperties(testContext);
ExtendedSelenium selenium = new ExtendedSelenium("localhost", RemoteControlConfiguration.DEFAULT_PORT,
testProps.getBrowser(), testProps.getServerUrl());
selenium.start();
selenium.useXpathLibrary("javascript-xpath");
selenium.allowNativeXpath("false");
return selenium;
}
}
The correct class code is:
public class SeleniumController {
private static Selenium selenium;
public static Selenium startNewSelenium(){
// if already exists stop it and replace with new one
stopSelenium();
selenium = createNewSelenium(getCurContext());
return selenium;
}
public static void stopSelenium() {
if(selenium != null){
selenium.stop();
selenium = null;
}
}
private static Selenium createNewSelenium(TestContext testContext){
TestProperties testProps = new TestProperties(testContext);
ExtendedSelenium selenium = new ExtendedSelenium("localhost", RemoteControlConfiguration.DEFAULT_PORT,
testProps.getBrowser(), testProps.getServerUrl());
selenium.start();
selenium.useXpathLibrary("javascript-xpath");
selenium.allowNativeXpath("false");
return selenium;
}
}