second test being missed in selenium webdriver - selenium-webdriver

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();
}
}

Related

My XML file doesn't seem to be pushing the values to my code. Causing my tests to be skipped

I am setting up test cases for practice and trying to feed the parameters from an XML file for the website url, and the desired browser if available. The Switch logic, and webdriver commands look solid, but maybe i missed something that makes it skip them entirely. Should output that login was successful on both occasions.
In the past I've simply fed the data in as variables, this is my first try with xml handling the data injection.
public class NewTest {
WebDriver driver;
#Test(dataProvider="getData")
public void login(String username,String password)
{
//Code to Login to the application
driver.findElement(By.xpath("//*[#id=\'myNavbar\']/ul/li[4]/a")).click();
driver.findElement(By.id("usernameLogin")).sendKeys(username);
driver.findElement(By.id("passwordLogin")).sendKeys(password);
driver.findElement(By.id("login")).click();
try
{
//verifying the presence of webelement
````````````````````````````````````````````
new WebDriverWait(driver, 10).until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.id("topMenu2")));
System.out.println("login success");
}
catch(Exception e)
{
System.out.println("Login failure");
}
driver.findElement(By.id("topMenu2")).click();
}
#DataProvider
public Object[][]getData() {
Object[][]data=new Object[2][2];
data[0][0]="pgGru";
data[0][1]="freezeray";
data[1][0]="pgAlmacho";
data[1][1]="freezeray";
return data;
}
#BeforeSuite
#Parameters({ "browsername", "url" })
public void setup(#Optional("Firefox")String browsername,String url) {
switch (browsername) {
case "IE":
WebDriver driver1;
driver1 = new InternetExplorerDriver();
System.setProperty("webdriver.IEDriverServer.driver", "D:\\Jarrrs\\Drivers\\IEDriverServer_win32");
driver1.get(url);
break;
case "Firefox":
WebDriver driver2;
driver2 = new FirefoxDriver();
System.setProperty("webdriver.geckodriver.driver","D:\\Jarrrs\\Drivers\\gecfkoDriver_win32");
driver2.get(url);
break;
case "chrome":
WebDriver driver3;
driver3 = new ChromeDriver();
System.setProperty("webdriver.chrome.driver, ","D:\\Jarrrs\\Drivers\\chromedriver_win32\\chromedriver.exe");
driver3.get(url);
break;
}
}
#AfterSuite
public void tearDown() {
driver.quit();
}
}
Right now the output is it is skipping the test cases for login and password
Expecting two passed or failed tests. Either one would be nice.
Newbie here. What do you mean by test is skipping? Are the actions within login() not being executed? I would put sys.out statements withing login() to check if the code is getting executed. How about adding a pause after page load? How about adding hardcoded value to username and password field to check if it is working fine?
Some times certain fields cannot be set by using Selenium's sendkeys. Need to use JavascriptExecutor to set the field values

Test Case breaking when running the application as a TestNG test

I wrote a java application to use the selenium webdriver to automate few web application tasks. They all worked fine when run as a Java application.
To use the TestNG reporting feature, I ran the application as a TestNG test instead of JAVA application. The same test which was working as JAVA application is failing when I run as testNG.
However, I'm guessing I've setup the TestNG properly since the first testcase which is used to login to the webapp is passing (webLogin method in the code below)
I'm using chromeDriver. I tried removing the main method to run it as testNG application. But it did not work. I made sure that the element path locators I'm using are still valid while using testNG.
package myPackage;
import java.util.NoSuchElementException;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.FluentWait;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.*;
import com.google.common.base.Function;
public class checkNavigation {
public static WebDriver driver;
public static WebDriverWait wait;
public static void main(String args[]) throws InterruptedException{
Configure();
wait = new WebDriverWait(driver, 30);
webLogin();
addClient();
addGoal();
addInsurance();
validateInputs();
endSession();
}
#BeforeTest
public static void Configure() {
System.setProperty("webdriver.chrome.driver", "/Users/divyakapa/Desktop/automation/chromedriver");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
driver.manage().timeouts().pageLoadTimeout(40, TimeUnit.SECONDS);
driver.get("https://example.com");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
#Test
public static void webLogin() {
getElement(By.xpath("//*[#id=\"id\"]")).sendKeys("admin");
getElement(By.xpath("//*[#id=\"pw\"]")).sendKeys("password");
getElement(By.xpath("//*[#id=\"ember383\"]/div/div/form/button/span")).click();
}
#Test
public static void addClient() {
getElement(By.xpath("//*[#id=\"ember744\"]/button/div")).click();
getElement(By.xpath("//*[#id=\"ember744\"]/div/button[1]/div[2]/div")).click();
getElement(By.xpath("//*[#id=\"newInputFirst\"]")).sendKeys("firstName");
getElement(By.xpath("//*[#id=\"newInputLast\"]")).sendKeys("lastName");
getElement(By.xpath("//*[#id=\"newPersonInputBirthday\"]")).sendKeys("1991");
Select location = new Select(driver.findElement(By.xpath("//*[#id=\"newUserInputProvince\"]")));
location.selectByVisibleText("Place1");
Select isRetired = new Select(driver.findElement(By.xpath("//*[#id=\"alreadyRetiredDropdown\"]")));
isRetired.selectByVisibleText("No");
Select age = new Select(driver.findElement(By.xpath("//*[#id=\"newRetirementAge\"]")));
age.selectByVisibleText("60");
getElement(By.xpath("//*[#id=\"data-entry-modal\"]/div[2]/div/div[1]/div[2]/button[2]")).click();
}
#Test
public static void addGoal() {
getElement(By.xpath("//*[#id=\"ember2328\"]/button/div")).click();
getElement(By.xpath("//*[#id=\"ember2328\"]/div/div[1]/div[2]/button[3]")).click();
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[#id=\"ember2464\"]/ul/li[1]/div/div/div[2]/div/span"))).click();
getElement(By.xpath("//*[#id=\"basicExpenseInputAmount\"]")).clear();
getElement(By.xpath("//*[#id=\"basicExpenseInputAmount\"]")).sendKeys("90000");
getElement(By.xpath("//*[#id=\"ember2563\"]/div/div[2]/div[2]/button[2]")).click();
// Add income
getElement(By.xpath("//*[#class=\"add-button \"]")).click();
getElement(By.xpath("//*[#data-test-model-type=\"income\"]")).click();
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[#class=\"list-group\"]/li[1]"))).click();
getElement(By.xpath("//*[#id=\"employmentInputName\"]")).clear();
getElement(By.xpath("//*[#id=\"employmentInputName\"]")).sendKeys("Company");
getElement(By.xpath("//*[#id=\"employmentInputSalary\"]")).sendKeys("95000");
getElement(By.xpath("//*[#id=\"employmentInputBonus\"]")).sendKeys("5000");
getElement(By.xpath("//*[#id=\"employmentInputBenefitsInKind\"]")).sendKeys("1000");
getElement(By.xpath("//*[#aria-label=\"Save\"]")).click();
}
#Test
public static void addInsurance() {
getElement(By.xpath("//*[#class=\"add-button \"]")).click();
getElement(By.xpath("//*[#data-test-model-type=\"protection\"]")).click();
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[#class=\"list-group\"]/li[1]"))).click();
getElement(By.xpath("//*[#id=\"termLifeName\"]")).clear();
getElement(By.xpath("//*[#id=\"termLifeName\"]")).sendKeys("BlueCrossBlueShield");
getElement(By.xpath("//*[#id=\"ukTermProtectionSalaryMultiplier\"]")).clear();
getElement(By.xpath("//*[#id=\"ukTermProtectionSalaryMultiplier\"]")).sendKeys("5");
Select empId = new Select(driver.findElement(By.xpath("//*[#id=\"termLifeInsuranceEmploymentId\"]")));
empId.selectByVisibleText("Company");
getElement(By.xpath("//*[#aria-label=\"Save\"]")).click();
}
#Test
public static void validateInputs() {
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
if(!(driver.findElements(By.xpath("//*[#data-test-accordion-header=\"goals\"]")).size() > 0)) throw new NullPointerException("Income Failed to ADD");
if(!(driver.findElements(By.xpath("//*[#data-test-accordion-header=\"income\"]")).size() > 0)) throw new NullPointerException("Income Failed to ADD");
if(!(driver.findElements(By.xpath("//*[#data-test-accordion-header=\"protection\"]")).size() > 0)) throw new NullPointerException("Income Failed to ADD");
}
public static WebElement getElement(final By locator) {
FluentWait<WebDriver> wait = new FluentWait<WebDriver>(driver).ignoring(NoSuchElementException.class);
WebElement element = wait.until(new Function<WebDriver, WebElement>() {
#Override
public WebElement apply(WebDriver arg0) {
return arg0.findElement(locator);
}
});
return element;
}
#AfterTest
public static void endSession() {
driver.close();
driver.quit();
}
}
Running the above code, the get the following error :
Default suite
Total tests run: 5, Failures: 4, Skips: 0
I also see that it takes a lot of time (about 10 seconds) before the page is logged in even though that test passes. This does not happen when I run the code as a Java application
Can you show which tests are actually failing? if you are looking for order in testng test execution, it doesn't come by default , so if you have to run test2 after test1 and test3 after test2 etc then you have to use priority(lower the number higher the priority) for ex,
#Test(priority=1)
public void Test1() {
}
#Test(priority=2)
public void Test2() {
}
#Test(priority=3)
public void Test3() {
}
hope this helps
No, testng never guarantees ordering by default
TestNG relies on reflection. The Java Reflection APIs does not guarantee the method order when we use it to introspect a class to find out what are the test methods that are available in it. So the order of independent methods (Methods that dont have either soft or hard dependency) execution is never guaranteed.
Soft dependency - This is usually achieved in TestNG by using the priority attribute for the #Test annotation. Its called a soft dependency because TestNG will continue to execute all the methods even though a previous method with a higher priority failed.
Hard dependency - This is usually achieved in TestNG by using either dependsOnMethods (or) dependsOnGroups attribute for the #Test annotation. It's called a hard dependency because TestNG will continue to execute a downstream method if and only if an upstream method ran successfully.
By default testng executes methods in alphabetical order of the method names. Typically you would not be using main method for testng. Annotations along with priority are used to set the sequence of executions
Testng framework will run the test methods in alphabetical order. I could see your test methods are dependent and it should in the order. You can set the priorities for your test methods the way you want it to run.
You can refer the below link to set the priority.
TestNG priority set

cucumber giving null pointer exception with multiple scenario in feature file

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.

How to integrate Selenium Webdriver with Cucumber

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

Getting ElementNotFound Exception in TestNG

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.

Resources