I'm using Selenium with Cucumber along with Gradle and TestNG. The same scenario runs for multiple parameters (Examples). Issue I'm facing is that for the first assertion success, browser (driver) closes. But for subsequent assertions failures, browser (driver) does not close, instead a new browser instance is launched for next set of values.
My Feature file
Feature: Using Contact Form
To test the functionality of contact form
Scenario Outline: Filling contact form
Given I am on Home Page of "http://room5.trivago.com/contact/"
And Dismiss cookies popup
When I enter message as "<message>"
And I enter full name as "<fullname>"
And I enter email as "<email>"
And I click on Submit button
Then I see success message
Examples:
|message|fullname|email|
|just some gibberish message|Ashish Deshmukh|ashish#deshmukh.com|
| |Ashish Deshmukh|ashish#deshmukh.com|
|just some givverish message| |ashish#deshmukh.com|
|just some gibberish message|Ashish Deshmukh| |
My StepDefination file
package stepDef;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import org.testng.Assert;
import pageObjectModels.ContactPageObjectModel;
import pageObjectModels.CookiesNoticePageObjectModel;
import java.util.logging.Logger;
public class Contact_Form extends Test_Base{
public static WebDriver driver;
public static ContactPageObjectModel objContact;
public static CookiesNoticePageObjectModel objCookies;
static Logger log = Logger.getLogger("com.gargoylesoftware");
#Given("^I am on Home Page of \"([^\"]*)\"$")
public void i_am_on_Home_Page_of(String arg1) throws Throwable {
// Write code here that turns the phrase above into concrete actions
System.setProperty("webdriver.chrome.driver", "D:\\Selenium Webdriver/chromedriver.exe");
driver = new HtmlUnitDriver(true);
driver = new ChromeDriver();
driver.get(arg1);
objContact = new ContactPageObjectModel(driver);
objCookies = new CookiesNoticePageObjectModel(driver);
}
#Given("^Dismiss cookies popup$")
public void dismiss_cookies_popup() throws Throwable {
// Write code here that turns the phrase above into concrete actions
objCookies.acceptCookies();
}
#When("^I enter message as \"([^\"]*)\"$")
public void i_enter_message_as(String arg1) throws Throwable {
// Write code here that turns the phrase above into concrete actions
objContact.enterMessage(arg1);
}
#When("^I enter full name as \"([^\"]*)\"$")
public void i_enter_full_name_as(String arg1) throws Throwable {
// Write code here that turns the phrase above into concrete actions
objContact.enterFullName(arg1);
}
#When("^I enter email as \"([^\"]*)\"$")
public void i_enter_email_as(String arg1) throws Throwable {
// Write code here that turns the phrase above into concrete actions
objContact.enterEmail(arg1);
}
#When("^I click on Submit button$")
public void i_click_on_Submit_button() throws Throwable {
// Write code here that turns the phrase above into concrete actions
objContact.clickSubmit();
}
#Then("^I see success message$")
public void i_see_success_message() throws Throwable {
// Write code here that turns the phrase above into concrete actions
String status = objContact.getSuccessStatus();
Assert.assertEquals(status, "Success");
driver.quit();
}
}
My build.gradle to run the test
group 'com.seleniumtestcucumber.mytest'
version '1.0-SNAPSHOT'
apply plugin: 'java'
apply plugin: 'idea'
configurations {
cucumberRuntime.extendsFrom testRuntime
}
task cucumber() {
dependsOn assemble, compileTestJava
doLast {
javaexec {
main = "cucumber.api.cli.Main"
classpath = configurations.cucumberRuntime + sourceSets.main.output + sourceSets.test.output
args = ['--plugin', 'pretty', '--glue', 'stepDef', 'src/test/java']
}
}
}
repositories {
mavenCentral()
jcenter()
}
dependencies {
compile 'org.seleniumhq.selenium:selenium-server:2.44.0'
// https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java
compile group: 'org.seleniumhq.selenium', name: 'selenium-java', version: '3.4.0'
compile 'org.testng:testng:6.1.1'
// https://mvnrepository.com/artifact/info.cukes/cucumber-testng
compile group: 'info.cukes', name: 'cucumber-testng', version: '1.2.5'
// https://mvnrepository.com/artifact/info.cukes/cucumber-java
compile group: 'info.cukes', name: 'cucumber-java', version: '1.2.5'
}
Console Log
Feature: Using Contact Form
To test the functionality of contact form
Scenario Outline: Filling contact form # features/Contact_Form.feature:5
Given I am on Home Page of "http://room5.trivago.com/contact/"
And Dismiss cookies popup
When I enter message as "<message>"
And I enter full name as "<fullname>"
And I enter email as "<email>"
And I click on Submit button
Then I see success message
Examples:
Starting ChromeDriver 2.29.461591 (62ebf098771772160f391d75e589dc567915b233) on port 42643
Only local connections are allowed.
Aug 10, 2017 4:21:10 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: OSS
Accepted cookies notice.
Entered message: just some gibberish message
Entered name: Ashish Deshmukh
Entered email: ashish#deshmukh.com
Clicked on Submit button.
Success
Scenario Outline: Filling contact form # features/Contact_Form.feature:15
Given I am on Home Page of "http://room5.trivago.com/contact/" # Contact_Form.i_am_on_Home_Page_of(String)
And Dismiss cookies popup # Contact_Form.dismiss_cookies_popup()
When I enter message as "just some gibberish message" # Contact_Form.i_enter_message_as(String)
And I enter full name as "Ashish Deshmukh" # Contact_Form.i_enter_full_name_as(String)
And I enter email as "ashish#deshmukh.com" # Contact_Form.i_enter_email_as(String)
And I click on Submit button # Contact_Form.i_click_on_Submit_button()
Then I see success message # Contact_Form.i_see_success_message()
Starting ChromeDriver 2.29.461591 (62ebf098771772160f391d75e589dc567915b233) on port 11801
Only local connections are allowed.
Aug 10, 2017 4:21:46 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: OSS
Accepted cookies notice.
Entered message:
Entered name: Ashish Deshmukh
Entered email: ashish#deshmukh.com
Clicked on Submit button.
Error
Scenario Outline: Filling contact form # features/Contact_Form.feature:16
Given I am on Home Page of "http://room5.trivago.com/contact/" # Contact_Form.i_am_on_Home_Page_of(String)
And Dismiss cookies popup # Contact_Form.dismiss_cookies_popup()
When I enter message as "" # Contact_Form.i_enter_message_as(String)
And I enter full name as "Ashish Deshmukh" # Contact_Form.i_enter_full_name_as(String)
And I enter email as "ashish#deshmukh.com" # Contact_Form.i_enter_email_as(String)
And I click on Submit button # Contact_Form.i_click_on_Submit_button()
Then I see success message # Contact_Form.i_see_success_message()
java.lang.AssertionError: expected [Success] but found [Error]
at org.testng.Assert.fail(Assert.java:94)
at org.testng.Assert.failNotEquals(Assert.java:513)
at org.testng.Assert.assertEqualsImpl(Assert.java:135)
at org.testng.Assert.assertEquals(Assert.java:116)
at org.testng.Assert.assertEquals(Assert.java:190)
at org.testng.Assert.assertEquals(Assert.java:200)
at stepDef.Contact_Form.i_see_success_message(Contact_Form.java:72)
at ✽.Then I see success message(features/Contact_Form.feature:12)
Starting ChromeDriver 2.29.461591 (62ebf098771772160f391d75e589dc567915b233) on port 22809
Only local connections are allowed.
Aug 10, 2017 4:22:39 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: OSS
Kindly suggest how to over come this. Is there a way I can use #BeforeTest #AfterTest in this?
You should read about cucumber hooks in details.
For your specific problem, you can use #After and #Before. This works for Junit Runner, never tested with TestNG but should work I guess as hooks are part of Cucumber and not JUnit/TestNG.
import cucumber.annotation.After;
import cucumber.annotation.Before;
#Before
public void beforeScenario()
{
System.setProperty("webdriver.chrome.driver", "D:\\Selenium Webdriver/chromedriver.exe");
driver = new HtmlUnitDriver(true);
driver = new ChromeDriver();
}
#After
public void afterScenario()
{
driver.quit()
}
Related
I have created a java/selenium/cucumber automation framework with 4 feature files each testing different functional area's.
I can run each of these within Eclipse as feature files and they all run fine.
However I am trying to figure out how I can run them all as a JUnit test so that I can generate the extent reports.
I run the mainRunner class as a Junit test like ..
The first feature runs fine but then the next three do not. A chrome browser is opened for each of these but
the site is not navigated to. The error
'org.openqa.selenium.NoSuchSessionException: Session ID is null. Using WebDriver after calling quit()?'
is shown in the console logs.
So is this issue to do with how I have set my feature files up to use the startBrowser, initBrowser and closeBrowser methods. Which are
defined in a seperate class 'BrowserInitTearDownStepDefinitions'?
All my feature files look like ..
Feature: Update a Computer in Database
-- left out details
#StartBrowser
Scenario: Start browser session
When I initialize driver
Then open browser
#MyTest4
Scenario Outline: Update a computer
-- left our details
Examples:
-- left out details
#CloseBrowser
Scenario: Close the browser
Then close browser
I have had a look at the other posts related to this message that reference the same error, but can't see a clear cut solution.
As the error would indicate I seem to be quitting the driver but then not reinitialising it for the next test. Although Im not sure why this
would be the case given that each feature file has the #StartBrowser and #CloseBrowser tags which should execute these methods. Below is my BrowserInitTearDownStepDefinitions class.
public class BrowserInitTearDownStepDefinitions {
//Initialises Chrome browser
#When("^I initialize driver$")
public void initializeDriver() {
System.out.println("initializeDriver runs");
System.setProperty("webdriver.chrome.driver","C:\\xxxx\\CucumberAutomationFramework\\src\\test\\java\\cucumberAutomationFramework\\resources\\chromedriver.exe");
WebDriverUtils.setDriver(new ChromeDriver());
}
//Opens Chrome browser and clicks in search input box
#Then("^open browser$")
public void openBrowser() {
System.out.println("Open Browser runs");
WebDriver driver = WebDriverUtils.getDriver();
driver.manage().window().maximize();
driver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS);
driver.manage().timeouts().setScriptTimeout(60, TimeUnit.SECONDS);
driver.get("https://computer-database.gatling.io/computers");
}
//Closes browser after all scenarios run and deletes cookies
#Then("^close browser$")
public void closeBrowser() {
System.out.println("Close Browser runs");
WebDriver driver = WebDriverUtils.getDriver();
driver.manage().deleteAllCookies();
driver.quit();
driver =null;
}
}
I create a new instance of the webdriver within my stepDefs file with ..
WebDriver driver = WebDriverUtils.getDriver()
The webdriver utils class code is ..
package cucumberAutomationFramework.utilityClasses;
import org.openqa.selenium.WebDriver;
public class WebDriverUtils {
private static WebDriver driver;
public static void setDriver(WebDriver webDdriver) {
if (driver == null) {
driver = webDdriver;
}
}
public static WebDriver getDriver() {
if (driver == null) {
throw new AssertionError("Driver is null. Initialize driver before calling this method.");
}
return driver;
}
}
Any advice would be much appreciated. Thanks.
My cucumber runner class cannot seem to find my step definition class, but it finds the feature file just fine.
Here is a snapshot of my very simple project structure:
Feature file:
Feature: Customer must be able to reach the Home Delivery page by clicking the Home Delivery button
Scenario: Test Home Delivery button
Given PS Restaurants web page is open
When User clicks on Home Delivery button
Then Home Delivery page should load
Step Definition class:
package stepDefinitions;
import java.util.concurrent.TimeUnit;
public class E_1_US_1 {
#Given("^PS Restaurants web page is open$")
public void ps_Restaurants_web_page_is_open() throws Exception {
// Write code here that turns the phrase above into concrete actions
throw new PendingException();
}
#When("^User clicks on Home Delivery button$")
public void user_clicks_on_Home_Delivery_button() throws Exception {
// Write code here that turns the phrase above into concrete actions
throw new PendingException();
}
#Then("^Home Delivery page should load$")
public void home_Delivery_page_should_load() throws Exception {
// Write code here that turns the phrase above into concrete actions
throw new PendingException();
}
}
Runner class:
package runner;
import org.junit.runner.RunWith;
import cucumber.api.junit.Cucumber;
import cucumber.api.CucumberOptions;
#RunWith(Cucumber.class)
#CucumberOptions(
features= {"src/features/Feature_1_1.feature"},
glue= {"src/stepDefinitions/E_1_US_1.java"}
)
public class Runner {
}
The output from running the Runner class as a JUnit test:
1 Scenarios ([33m1 undefined[0m)
3 Steps ([33m3 undefined[0m)
0m0.040s
You can implement missing steps with the snippets below:
#Given("^PS Restaurants web page is open$")
public void ps_Restaurants_web_page_is_open() throws Exception {
// Write code here that turns the phrase above into concrete actions
throw new PendingException();
}
#When("^User clicks on Home Delivery button$")
public void user_clicks_on_Home_Delivery_button() throws Exception {
// Write code here that turns the phrase above into concrete actions
throw new PendingException();
}
#Then("^Home Delivery page should load$")
public void home_Delivery_page_should_load() throws Exception {
// Write code here that turns the phrase above into concrete actions
throw new PendingException();
}
I just copied and pasted the output into my step definitions class and it still won't recognize the step definitions class. Earlier it was saying that there was no matching glue code for each step in the scenario, but that went away after I closed and reopened the feature file.
You can update your runner class as below:
package runner;
import org.junit.runner.RunWith;
import cucumber.api.junit.Cucumber;
import cucumber.api.CucumberOptions;
#RunWith(Cucumber.class)
#CucumberOptions(
features= {"src/features"}, //It will pick all the feature files located in this folder
glue= {"stepDefinitions"} //Only package name is required here.
)
public class Runner {
}
The url is not getting loaded completely, getting an error as "[SEVERE]: Timed out receiving message from renderer: -0.010" with below configurations:
Please pardon me since new to this.
Browser: Chrome 64
Selenium: 3.10.0
Build tool: maven (pom.xml)
Testng: 6.8
Scenario:
Use OWASP ZAP APIs with selenium functional test cases. below is the script:
public void login() {
// driver.get(BASE_URL);
driver.navigate().to(BASE_URL);
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
driver.findElement(By.xpath("//span[#class='btn btn-link']")).click();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
}
#BeforeTest
public void setup() {
zapScanner = new ZAProxyScanner(ZAP_PROXYHOST,ZAP_PROXYPORT,ZAP_APIKEY);
zapScanner.clear(); //Start a new session
zapSpider = (Spider)zapScanner;
log.info("Created client to ZAP API");
driver = DriverFactory.createProxyDriver("chrome",createZapProxyConfigurationForWebDriver(), CHROME_DRIVER_PATH);
// driver = DriverFactory.createProxyDriver("firefox",createZapProxyConfigurationForWebDriver(), FIREFOX_DRIVER_PATH);
myApp = new MyAppNavigation(driver);
// myApp.registerUser(); //Doesn't matter if user already exists, bodgeit just throws an error
System.out.println("before test is done");
}
#Test
public void testSecurityVulnerabilitiesAfterLogin() {
System.out.println("started test");
myApp.login();
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
// myApp.navigateAfterLogin();
log.info("Spidering...");
spiderWithZap();
log.info("Spider done.");
}
Chrome browser is launched with the given base_url however it the url doesn't load completely and gives an error as shown in the attached screen shot.
I am trying to running selenium webdriver using eclipse.Unfortunately i face the following issue:
click here for the snapshot
and the code is,
package myproject;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class MyClass {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.setProperty("webdriver.gecko.driver", "K:\\New folder\\geckodriver-v0.18.0-win64\\geckodriver.exe");
WebDriver driver = new FirefoxDriver(); driver.get("http://only-testing-blog.blogspot.in");
String i = driver.getCurrentUrl();
System.out.println(i); driver.close();
}
}
UPDATE:
If you right click on your project and "Run as... Java application" and you have multiple main methods in your project, eclipse doesn't know which one to start so it asks which class. The solution is to right click on your class and "Run as...". After that you can just press "Run".
no matter what I do selenium doesn't accept my firefox path in the console where I launch it from. Keep getting the same error.
I also set the path as an environment variable in win 7 64.
I'm pretty much a virgin when it comes to selenium. Trying to run my first JUNIT test.
Here is the message from selenium.
21:46:43.481 INFO - Command request: getNewBrowserSession[*chrome, http://compendiumdev.co.uk/, ] on session null
21:46:43.497 INFO - creating new remote session
21:46:43.544 INFO - Got result: Failed to start new browser session: java.lang.RuntimeException: java.lang.RuntimeException: Firefox could not be found in the path!
Please add the directory containing ''firefox.exe'' to your PATH environment
variable, or explicitly specify a path to Firefox like this:
*firefox c:\blah\firefox.exe on session null
Below is my java code
package com.eviltester.seleniumtutorials;
import com.thoughtworks.selenium.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class MyFirstSeleniumTests {
Selenium selenium=null;
#Before
public void setUp() throws Exception {
selenium = new DefaultSelenium("localhost", 4444, "*chrome",
http://compendiumdev.co.uk/");
selenium.start();
}
#Test
public void testExported() throws Exception {
selenium.open("/selenium/search.php");
selenium.type("q", "Selenium-RC");
selenium.click("name=btnG");
}
#After
public void tearDown() throws Exception {
selenium.stop();
}
}
Thank you for the help.