Test Steps
public class TestSmoke {
WebDriver driver;
#Given("^open firefox and start application$")jjj
public void open_firefox_and_start_application() throws Throwable {
driver=new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(40, TimeUnit.SECONDS);
driver.get("https://example.com");
}
**Scenario 1**
#When("^I click on Login$")
public void I_click_on_Login() throws Throwable {
driver.findElement(By.xpath("//a[contains(.,'Login')]")).click();
}
#When("^enter valid \"([^\"]*)\" and valid \"([^\"]*)\"$")
public void enter_valid_and_valid(String uname, String pass) throws Throwable {
driver.findElement(By.id("Username")).sendKeys(uname);
driver.findElement(By.id("Password")).sendKeys(pass);
}
#Then("^Click on login and User should be able to login successfully$")
public void Click_on_login_and_User_should_be_able_to_login_successfully() throws Throwable {
driver.findElement(By.id("loginUser")).click();
}
jkjbjkkjhjknjkbjkhjkbjbjbbjbnmbbnmb
**Scenario 2:**
#Given("^Click on shop for carts$")
public void Click_on_shop_for_carts() throws Throwable {
hhjbhbhgjbkjbhlhihjbhbb
driver.findElement(By.xpath("//span[text()='Shop for Parts']")).click();
}
#Given("^select plates$")
public void select_plates() throws Throwable {
driver.findElement(By.xpath("//a[contains(.,'Plates ')]")).click();
}
#When("^I click on drsired product$")
public void I_click_on_drsired_product() throws Throwable {
driver.findElement(By.xpath("//a[#data-itemnumber='PLT01096096046']")).click();
}
#When("^click on item increment$")
public void click_on_item_increment() throws Throwable {
WebElement ele=driver.findElement(By.xpath("//i[contains(#class,'fa fa-caret-up')]"));
for(int i=0;i<=3;i++)
{
ele.click();
}
}
#When("^Click on buy now$")
public void Click_on_buy_now() throws Throwable {
driver.findElement(By.xpath("//button[contains(.,'Buy Now')]")).click();
}
#Then("^Product should be added to the cart successfully$")
public void Product_should_be_added_to_the_cart_successfully() throws Throwable {
}
Feature File
Feature: Test test Smoke scenario
Scenario: Test login with valid credentials
Given open firefox and start application
When I click on Login
And enter valid "s#yopmail.com" and valid "passw0rd"
Then Click on login and User should be able to login successfully
Scenario: Test shop for cart
Given Click on shop for carts
And select plates
When I click on drsired product
And click on item increment
And Click on buy now
Then Product should be added to the cart successfully
Test runner
#RunWith(Cucumber.class)
#Cucumber.Options(features="features",glue={"steps"})
public class TestRunnr {
While i am running this cucumber script its throwing an NullPointer Exception :
java.lang.NullPointerException
at steps.testmoke.Click_on_shop_for_carts(testSmoke.java:47)
at ?.Given Click on shop for carts(MyApplication.feature:11)
First scenario is executing successfully but second scenario is not executing.I am login in a ecommerce website and try to click on shop for parts .
Each scenario creates a fresh instance of all the step definitions.
In your case you instantiate the driver in the Given step public void open_firefox_and_start_application() so the first scenario is successful.
Now for the second scenario a new instance of your class has a webdriver which is null and you are not calling the earlier step to instantiate it.
You can use a static webdriver, but you will run into issues with parallel tests. If you are planning for parallel tests look up ThreadLocal to make sure your webdriver is attached to the specific thread.
Another way could be to move the login tests to a separate file. For the other scenarios move the login steps into the Background cucumber tag. This way the webdriver will be instantiated for each scenario. But you will need to decide if you want to keep logged in across scenarios, delete cookies or a new browser for each scenario.
Related
Their are numerous resources on internet but I couldn't find a simple answer to my problem.
I want my test case to fail and report a one liner meaningful message instead of full stack trace.
I tried using try, catch, if, else but I want my test to fail not to pass and throw message.
Scenario - Load url, if url doesn't load throw error and abort test and move to next iteration of loading next url
Any solution ?
You can try... try catch
try {
doStuff();//this code is failing
}
catch (YourExpectedException e){ //catch the correct exception here
//this passes your custom message AND the caught exception
//should also stop the test
throw new AssertionError("This is my custom message", e);
}
There are two ways how to do it. I would like to suggest you the most simple and beautiful ways.
1) Checking exception and if exception on of you specify you will execute some code or do something. Here is the example:
#AfterMethod
public void afterMethod(ITestResult result) throws IOException {
Throwable exception = result.getThrowable();
if (exception instanceof org.openqa.selenium.TimeoutException
||
exception instanceof org.openqa.selenium. NoSuchElementException) {
Assert.fail("Some message or code");
}
}
2)
You can implement WebDriverEventListener in your project.
What it means?
It means that WebDriver allow to execute some logic before and after some events. You can add try-catch in the implementation of methods.
Example:
#Override
public void beforeFindBy(By by, WebElement webElement, WebDriver webDriver) {
// your code
}
#Override
public void afterFindBy(By by, WebElement webElement, WebDriver webDriver) {
// your code
}
#Override
public void beforeClickOn(WebElement webElement, WebDriver webDriver) {
// your code
}
#Override
public void afterClickOn(WebElement webElement, WebDriver webDriver) {
// your code
}
Here is more detail example: link
I am totally new to selenium so learning from scratch.
I am creating a test where I want to test each link, verify its has gone to the correct page and then return to the page i started on. The first section is logging into the site and verifying i am on the correct page but I cannot get the second #Test to be executed.
#Test
public void LoginTest() {
driver.navigate().to("https://test.barclays.lifestyleservicesgroup.co.uk/");
driver.findElement(By.xpath(".//*[#id='security']")).click();
driver.findElement(By.xpath(".//*[#id='EmailAddress']")).sendKeys("autobarc001#test.lifestylegroup.co.uk");
driver.findElement(By.xpath(".//*[#id='Password']")).sendKeys("Abcd1234!");
driver.findElement(By.xpath(".//*[#id='main-content']/div[2]/div[2]/form/div[1]/div[2]/span/input")).click();
Assert.assertTrue(driver.findElement(By.xpath(".//*[#id='main-content']/div[2]/h1")).isDisplayed());
}
//Checking claim process link on homepage
#Test
public void claimProcessTest (){
driver.findElement(By.xpath(".//*[#id='helpful-info']/div[2]/ul/li[1]/a")).click();
Assert.assertTrue(driver.findElement(By.xpath(".//*[#id='main-content']/div[2]/div[1]/h1")).isDisplayed());
driver.findElement(By.xpath(".//*[#id='current-nav']/a")).click();
}
//Closing browser after execution
#AfterClass
public static void tearDown () {
driver.close();
}
}
I am looking to integrate Selenium Webdriver with Cucumber. Please let me know if anyone has already implemented the same.
You need the Cucumber-JVM. After that when you write feature files you need to define their steps definitions using Selenium (this could be your POM Based project or direct api call).
Below are links on how to go about implementing this
Links
http://cukes.info/install-cucumber-jvm.html
http://cukes.info/running.html
Snippets
Feature Sample
Feature: Page Verification
Scenario: Verify Page
Given User navigated to Page
And user SignUp
Then user should be redirected to Login
When User click "https://page.com/userLogin/"
Then User Should verify "Login"
And close browsers
Steps Definition
public class StepsDefinitions {
WebDriver driver = null;
#Given("^User navigated to \"([^\"]*)\"$")
public void gotoSite(String link) throws Throwable {
driver = new FirefoxDriver();
driver.navigate().to(link);
}
#When("^User click \"([^\"]*)\"$")
public void clickSignUp(String link) throws Throwable {
driver.findElement(By.linkText(link)).click();
}
#Then("^User Should verify \"([^\"]*)\"$")
public void User_Should_verify(String title) {
Assert.assertTrue( driver.getTitle().equals(title));
}
#And("^close browsers$")
public void close_browsers() throws Throwable {
driver.close();
}
I would recommend you to go through the detailed quick set-up instructions in the link.
Resource: Blog Thomas Sundberg
The following code is for login and then click on Create quest Link. It does not click on the link and gives ElementNotFound exception and skips the test. It just logs in and logout. Please Help
public class Edit_Question {
WebDriver driver = new FirefoxDriver();#
BeforeTest
public void load() {
driver.get("Page url");
}
# Test
public void login() throws InterruptedException {
driver.findElement(By.id("userid")).sendKeys("4060#jhg.com");
driver.findElement(By.id("password")).sendKeys("mpcyn2");
driver.findElement(By.id("emLoginLink")).click();
Thread.sleep(10000);
}# Test
public void ques() throws InterruptedException {
//select create questions
driver.findElement(By.xpath("//xpath link")).click(); //throws ElementNotFound exception
Thread.sleep(5000);
}# Test
public void logout() {
//logout
driver.findElement(By.partialLinkText("SeeharackTest1, SherrodUATT")).click();
driver.findElement(By.id("logoutLink")).click();
}
# AfterSuite
public void close() {
driver.close();
}
}
The order of execution is not gauranteed. You need to use dependOnMethods to gaurantee order here. So ques should depend on login and logout should depend on ques to gaurantee the order of execution.
Other observations :
1. Try using #BeforeClass instead of #BeforeTest and #AfterClass instead of #AfterSuite
2. Avoid using sleeps wherever possible. Wait for a particular element instead.
3. Shouldn't this entire flow be one testcase?
Hope it helps.
I have the following Selenium script for opening alert on rediff.com:
public class TestC {
public static void main(String[] args) throws InterruptedException, Exception {
System.setProperty("webdriver.chrome.driver", "driver/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://www.rediff.com/");
driver.findElement(By.xpath("//*[#id='signin_info']/a[1]")).click();
driver.findElement(By.id("btn_login")).click();
Thread.sleep(5000);
Alert alert=driver.switchTo().alert();
alert.accept();
}
}
This very same script is working fine in Firefox and IE9, however using Google Chrome after opening the alert, rest of the code is not working. The main thing is that does not shows any exception, error or anything.
Please provide any solution as soon as possible.
Thanks a lot!
Note: If we need to change any setting of browser or any thing please let me know.
Selenium version:Selenium(2) Webdriver
OS:Windows 7
Browser:Chrome
Browser version:26.0.1410.64 m
I'm pretty sure your problem is a very common one, that's why i never advise using Thread.sleep(), since it does not guarantee the code will run only when the Alert shows up, also it may add up time to your tests even when the alert is shown.
The code below should wait only until some alert is display on the page, and i'd advise you using this one Firefox and IE9 aswell.
public class TestC {
public static void main(String[] args) throws InterruptedException, Exception {
System.setProperty("webdriver.chrome.driver", "driver/chromedriver.exe");
WebDriver driver = new ChromeDriver();
WebDriverWait wait = new WebDriverWait(driver, 5);
driver.get("http://www.rediff.com/");
driver.findElement(By.xpath("//*[#id='signin_info']/a[1]")).click();
driver.findElement(By.id("btn_login")).click();
wait.until(ExpectedConditions.alertIsPresent());
Alert alert = driver.switchTo().alert();
alert.accept();
}
}
Mostly all that is done here, is changing Thread.sleep(), for a condition that actually will only move forward on the code as soon a alert() is present in the page. As soon as someone does, it wil switch to it and accept.
You can find the Javadoc for the whole ExpectedConditions class here.
Unfortunately AlertIsPresent doesn't exist in C# API
http://selenium.googlecode.com/git/docs/api/dotnet/index.html
You can use something like this:
private static bool TryToAcceptAlert(this IWebDriver driver)
{
try
{
var alert = driver.SwitchTo().Alert();
alert.Accept();
return true;
}
catch (Exception)
{
return false;
}
}
public static void AcceptAlert(this IWebDriver driver, int timeOutInSeconds = ElementTimeout)
{
new WebDriverWait(driver, TimeSpan.FromSeconds(timeOutInSeconds)).Until(
delegate { return driver.TryToAcceptAlert(); }
);
}