java unit test with selenium getting nullpointer exception for #inject function - java

I am trying to unit test Sign On method in selenium. My Sign On method is injecting other pages which is taking webdriver in turn.
SignOn.java
import ...
#PageObject
public class SignOn {
#Inject
BasePage basepage
public void signOn(driver,user,password){
basepage.clickhamburgermenu() #This line is not instantiated when
unit testing but works fine when just running this file.
}
BasePage.java
import ...
public class BasePage {
Map<String, String> data;
WebDriver driver;
#Inject
public BasePage(WebDriver driver) {
this.driver = driver;
PageFactory.initElements(driver, this);
}
public void clickHamburgerMenu() {
if(driver.findElements(By.cssSelector(hamburgerMenu)).size() > 0)
{
WebElement burgerMenu = driver.findElement(By.cssSelector(hamburgerMenu));
if(burgerMenu.isDisplayed()){burgerMenu.click();}
}
}
SignOntest.java
import ...
public class signOnTest{
#BeforeMethod
public void setUp() {
webDriver = new ChromeDriver();
signOn = new SignOn();
}
#Test
public void testSignOn() {
webDriver.get("www.facebook.com");
SignOn.SignOn(webDriver,"user","password");
}
}
Here, I wanna unit test sign-on method but it fails on basepage initiation. I am not that pro in dependency injection. Anything helps.

Related

Multiple instances of browser opening up when running test through webdriver manager

I am new to Selenium, so basically whenever I ran my test, it would open up the URL which I have mentioned in my test. In my same Test I have also mentioned to fill the username and Password.
But somehow once the browser gets launched and redirect to the URL, it opens up another instance of blank browser failing my script that element not found.
Please help me here.
///////////////////////////////////////////////////////////////////////////
public class TruefillTest extends BaseClass {
public Truefill truefill()
{
WebDriver driver=InitializeDriver();
return new Truefill(driver);
}
#Test
public void userLoginIntoTheSystem()
{
truefill().dashBoard().Url();
truefill().dashBoard().EnterUsername("bjdgfe#swcwr.com");
truefill().dashBoard().EnterPassword("Test1234");
}
///////////////////////////////////////////////
public class Truefill {
private WebDriver driver;
public Truefill(WebDriver driver) {
this.driver=driver;
}
public DashBoardPage dashBoard()
{
return new DashBoardPage(driver);
}
////////////////////////////////////////////////////////////
public class DashBoardPage {
private final WebDriver driver;
By Username= By.xpath("//input[#name='name']");
By Password= By.xpath("//input[contains(#id,'exampleInputPassword1')]");
public DashBoardPage(WebDriver driver) {
this.driver=driver;
}
public void Url()
{
driver.get("https://rahulshettyacademy.com/angularpractice/");
}
public void EnterUsername(String username)
{
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.findElement(Username).sendKeys(username);
}
public void EnterPassword(String password)
{
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.findElement(Password).sendKeys(password);
}
////////////////////////////////////////////////////////////
public class BaseClass {
WebDriver driver;
public WebDriver InitializeDriver()
{
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
return driver;
}
}
Each call to the truefill() method initializes a new instance of WebDriver. Since your test is calling it multiple times, it will start a new browser instance on each line. Instead, store the DashboardPage in a local variable:
#Test
public void userLoginIntoTheSystem() {
DashBoardPage dashBoardPage = truefill().dashBoard();
dashBoardPage.Url();
dashBoardPage.EnterUsername("bjdgfe#swcwr.com");
dashBoardPage.EnterPassword("Test1234");
}
You might also want to use a setup method to initialize the Truefill instance, rather than creating it on demand:
private Truefill truefill;
#BeforeEach
public void initializeTruefill() {
WebDriver driver = InitializeDriver();
truefill = new Truefill(driver);
}
#Test
public void userLoginIntoTheSystem() {
DashBoardPage dashBoardPage = truefill.dashBoard();
dashBoardPage.Url();
dashBoardPage.EnterUsername("bjdgfe#swcwr.com");
dashBoardPage.EnterPassword("Test1234");
}
This assumes JUnit 5. If you're using JUnit 4, the annotation is #Before instead of #BeforeEach.

NoSuchElementException using WebDriverWait

I would really like to understand why when approaching locating an element the exact same way as previously failing.
NoSuchElementException : Caused by: org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//span[contains(text(),'Add')]"}
I have also tried to use something like the following but it also failed, so in order for me write a good automation code i need to get my knowledge straight with WebDriverWait, so i would appreciate somebody with knowledge to spend some time on this inquiry.
It does locates if i have xpath like this :
//body/div[#id='root']/div[1]/div[1]/div[1]/div[2]/div[1]/div[1]/div[2]/div[1]/div[2]/div[1]/div[2]/div[1]
public void clickOnAddVehicleButton() {
wait.until(ExpectedConditions.visibilityOf(addVehicleButton));
vehicles.addVehicleButton.click();
}
I am not new into Java but i am new into automation hence some areas of knowledge is missing, i ha
Base class:
public class BasePage {
protected final WebDriver driver;
protected final WebDriverWait wait;
public BasePage(WebDriver driver) {
this.driver = driver;
this.wait = new WebDriverWait(driver,5);
PageFactory.initElements(new AjaxElementLocatorFactory(driver, 10), this);
}
}
The component where that button should be present :
public class Vehicles extends BasePage {
private static Vehicles vehicles;
private Vehicles(WebDriver driver) {
super(driver);
}
#FindBy(xpath = "//span[text(),'Add']")
public WebElement addVehicleButton;
public static Vehicles vehiclesInstance(WebDriver driver) {
return vehicles == null ? vehicles = new Vehicles(driver) : vehicles;
}
public void clickOnAddVehicleButton() {
vehicles.addVehicleButton.click();
}
Function in the service class:
public void addVehicle(String vehicleName, String numberPlate) {
myAccountService.myAccountPage()
.clickOnVehiclesTab();
vehicles.fillInVehicleName(vehicleName)
.fillInVehicleNumberPlate(numberPlate)
.clickOnAddVehicleButton();
}
WebDriverSettings for test :
public class WebDriverSettings {
protected WebDriver driver;
#Before
public void setUp() {
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
loginToDevEnvironment();
}
And finally my test class where i am calling the service method:
public class VehicleServiceTest extends WebDriverSettings {
private VehiclesService vehiclesService;
#Before
public void setUp(){
super.setUp();
CookieService.cookieServiceInstance(driver).acceptCookies();
HomePageService.homePageServiceInstance(driver).clickOnMyAccountTab();
LoginService.loginServiceInstance(driver).login(loginCorrectData());
HomePageService.homePageServiceInstance(driver).clickOnMyAccount();
vehiclesService = VehiclesService.vehiclesServiceInstance(driver);
}
#Test
public void shouldAddVehicle(){
vehiclesService.addVehicle("test-vehicle","test-test");
Assert.assertEquals(1,vehiclesService.getVehicles().listOfAddedVehicles().size());
}

Null pointer exception in selenium cucumber JUnit Framework

Can someone tell the issue in my code for null pointer exception?
Error Message in console
=>test.pages.HomePage#31e75d13<=
[31mFailed scenarios:[0m
[31mE2E_Test.feature:3 [0m# Scenario: Test scenario
1 Scenarios ([31m1 failed[0m)
10 Steps ([31m1 failed[0m, [36m8 skipped[0m, [32m1 passed[0m)
0m12.461s
java.lang.NullPointerException
at org.openqa.selenium.support.pagefactory.DefaultElementLocator.findElement(DefaultElementLocator.java:69)
at org.openqa.selenium.support.pagefactory.internal.LocatingElementHandler.invoke(LocatingElementHandler.java:38)
at com.sun.proxy.$Proxy17.sendKeys(Unknown Source)
at test.pages.HomePage.enterSearchText(HomePage.java:31)
at stepDefinitions.Steps.he_search_for(Steps.java:49)
at ✽.When he search for "test"(E2E_Test.feature:5)
Although I am getting the driver object and its not coming as Null as well but still getting a null pointer exception.
I am trying to run the selenium webdriver code to automate some test case. Here i am trying to open google.com and wants to enter some text in search box but after opening the google.com, when the execution reaches searchtextbox.sendkeys("test"), it gives null pointer exception. I tried debugging it to see if the homepage class object is coming as null or not but its showing the value and not null.
This is the test base class that i am using to initiate the google site and maximize the code
public class TestBase {
public static WebDriver driver;
public static Properties prop;
public static EventFiringWebDriver e_driver;
public static WebEventListener eventListener;
public TestBase() {
try {
prop = new Properties();
FileInputStream ip = new FileInputStream(System.getProperty("user.dir") + "/src/main/java/test" +
"/config/config.properties");
prop.load(ip);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
// This method is used to initiatize the site url
public static void initialization(String url) {
String browserName = prop.getProperty("browser");
if (browserName.equals("chrome")) {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\test\\Downloads\\driver\\chromedriver.exe");
driver = new ChromeDriver();
}
e_driver = new EventFiringWebDriver(driver);
// Now create object of EventListerHandler to register it with EventFiringWebDriver
eventListener = new WebEventListener();
e_driver.register(eventListener);
driver = e_driver;
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
driver.manage().timeouts().pageLoadTimeout(TestUtil.PAGE_LOAD_TIMEOUT, TimeUnit.SECONDS);
driver.manage().timeouts().implicitlyWait(TestUtil.IMPLICIT_WAIT, TimeUnit.SECONDS);
if (url == "google") {
driver.get(prop.getProperty("url"));
}
}
}
// Steps Definition file (Steps.java): This is the step defintion file // there is a function he_search_for called where the exception occurs
public class Steps extends TestBase {
WebDriver driver;
TestUtil testUtil;
HomePage homePage;
#Given("^user is on google home page$")
public void user_is_on_google_home_page() throws Throwable {
initialization("google");
testUtil = new TestUtil();
homePage = new HomePage(driver);
}
#When("^he search for \"([^\"]*)\"$")
public void he_search_for(String arg1) throws InterruptedException {
System.out.print("=>" + homePage + "<=");
homePage.enterSearchText();
}
}
// HomePage Class is used to define all the page elements here in this class, i used enterSearchText function to enter the text in a search box.
public class HomePage extends TestBase {
#FindBy(name = "q")
WebElement searchTextBox;
WebDriver driver;
// Initializing the Page Objects:
public HomePage(WebDriver driver) {
this.driver = driver;
PageFactory.initElements(driver, this);
}
public void enterSearchText() {
searchTextBox.sendKeys("Test");
}
}
Problem lies within your code design pattern between Classes Steps & TestBase. Please note
First, Class Steps is extending TestBase which already has WebDriver variable declared & initialized in it. So you do not need to again define WebDriver instance with in Steps. So please remove "WebDriver driver;" from below peace of code.
public class Steps extends TestBase {
WebDriver driver;
TestUtil testUtil;
Second, Please do not declare WebDriver as static variable. Kindly declare it as Non-static as Keeping static may create problem during parallel execution as well.
public class TestBase {
public WebDriver driver;
Making WebDriver instance as non-static and having it as Thread safe
TestBase.java
public class TestBase {
public WebDriver driver;
public static Properties prop;
// This method is used to initiatize the site url
public synchronized void initialization(String url) {
String browserName = prop.getProperty("browser");
if (browserName.equals("chrome")) {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\test\\Downloads\\driver\\chromedriver.exe");
driver = new ChromeDriver();
DriverManager.setWebDriver(driver);
}
}
}
DriverManager.java
import org.openqa.selenium.WebDriver;
public class DriverManager {
public static ThreadLocal<WebDriver> dr = new ThreadLocal<WebDriver>();
public static WebDriver getDriver() {
return dr.get();
}
public static void setWebDriver(WebDriver driver) {
dr.set(driver);
}
}
The problem is here
public class Steps extends TestBase {
WebDriver driver;
TestUtil testUtil;
HomePage homePage;
#Given("^user is on google home page$")
public void user_is_on_google_home_page() throws Throwable {
initialization("google");
testUtil = new TestUtil();
homePage = new HomePage(driver);
}
#When("^he search for \"([^\"]*)\"$")
public void he_search_for(String arg1) throws InterruptedException {
System.out.print("=>" + homePage + "<=");
homePage.enterSearchText();
}
}
The WebDriver driver is null. You initialized WebDriver in initialization("google") method but you don't assign the value of created WebDriver to your driver
Additional line of code might help you.
#Given("^user is on google home page$")
public void user_is_on_google_home_page() throws Throwable {
initialization("google");
this.driver = TestBase.driver; //asign initialized WebDriver to this instance variable
testUtil = new TestUtil();
homePage = new HomePage(driver);
}
You can also remove the local WebDriver driver variable. Since TestBase contains static WebDriver, you can just use it directly since you use inheritance.
However, I highly suggest reading about WebDriverFactory or any similar term, like WebDriverManager. Anything to handle WebDriver instantiation without creating a static WebDriver. It will cause a lot of issues in the future with parallel execution.

Unable to use locators in #Test Junit Selenium web driver

I am new in JUnit Selenium, and I found problem.
I cannot find elements using locator in #Test method. I dont have predictive search when I type driver. I can if I type into #Before.
E.g I cant type
#Test
..
driver.findElement(By.id("gs_htif0")).sendKeys("blabla");
My class contains -
#Before
public void setUp() throws Exception {
WebDriver driver;
System.setProperty("webdriver.gecko.driver", "C:\\geckodriver.exe");
driver = new FirefoxDriver();
String baseURL = "https://www.google.com";
driver.get(baseURL);
}
#Test
public void test() {
driver.**___PROBLEM___**
}
#After
public void tearDown() throws Exception {
}
That's because you've declared
WebDriver driver;
locally within the setUp method which is also annotated using #Before in your case.
You shall move this to the class level and use further as -
public class SomeTest {
WebDriver driver;
#Before
public void setUp() throws Exception {
...
driver = new FirefoxDriver();
...
driver.get(baseURL);
}
#Test
public void test() {
driver.getTitle(); //just an example
}
.... // other methods
}

Checking page status programmatically

I have been writing Selenium test for web application and there seem to be multiple instances of Internal Server Error in application in case of Internal Server Error, application displays custom error page and and error id is displayed to user to pursue matter with technical team, in case user encounter it.
This makes it a little laborious to debug the test failures during Selenium execution.
I was thinking to use some mechanism to keep polling a page with each step executed in test to find if there was any instance of Internal Server error, And this is when I came across Junit Rule and thought of writing a custom annotation for it, some thing like -
public class SelTestCase {
protected WebDriver driver;
#Before
public void startDriver() {
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("http://www.google.com/");
}
#After
public void closeDriver() {
driver.quit();
}
}
public class GoogleSearchTest extends SelTestCase {
#Rule
PageChecker pageChecker = new PageChecker();
#Test
#CheckPage
public void testGoogleSearch() {
GoogleHomePage googleHomePage = PageFactory.initElements(driver,
GoogleHomePage.class);
googleHomePage.searchGoogle("Selenium HQ");
assert driver.getPageSource().contains("seleniumhq") : "Selenium headquarter search failed";
}
}
SelTestCase class creates instance of WebDriver to execute test, And here is the PageChecker class -
public class PageChecker extends SelTestCase {
#Retention(RetentionPolicy.RUNTIME)
#Target({ElementType.METHOD})
public #interface CheckPage {
// page check should take place here (Though not sure if it is right place)
// like if(driver.getPageSource.contains("Internal Server Error") {throw Exception ("Err")}
}
}
This is what I am stuck with, how do I proceed with CheckPage annonations?
IMHO there are two solutions to your problems. If the feature is only needed by a small part of your tests, then I would not use a rule. Instead add a single line errorChecker.checkPage(driver) to each tests and implement the check in this method.
If you need it for almost all your tests:
Convert SelTestCase to a rule by extending ExternalResource.
public class WebDriverRule extends ExternalResource {
public WebDriver driver;
#Override
protected void before() {
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("http://www.google.com/");
}
#Override
protected void after() {
driver.quit();
}
}
Add the page check code to the rule by extending Verifier.
public class PageChecker extends Verifier {
private WebDriverRule webDriverRule;
private enabled = true;
public PageChecker(WebDriverRule webDriverRule) {
this.webDriverRule = webDriverRule;
}
public void disable() {
this.enabled = false;
}
#Override
public void verify() {
if(enabled && notValid())
throw new AssertionError("foo");
}
private boolean notValid() {
WebDriver driver = webDriverRule.driver;
//do something with driver
}
}
Use org.junit.rules.RuleChain to control the execution order of the two rules.
public class GoogleSearchTest {
private WebDriverRule webDriverRule = new WebDriverRule();
private PageChecker pageChecker = new PageChecker(webDriverRule);
#Rule
public RuleChain driverAroundPageChecker
= RuleChain.outerRule(webDriverRule).around(pageChecker);
#Test
public void testGoogleSearch() {
GoogleHomePage googleHomePage = PageFactory.initElements(driver,
GoogleHomePage.class);
googleHomePage.searchGoogle("Selenium HQ");
assert driver.getPageSource().contains("seleniumhq") : "Selenium headquarter search failed";
}
#Test
public void testWithouPageCheck() {
pageChecker.disable();
//here is your real test
}
}

Categories