qait qait - 3 months ago 108
C# Question

error System.NullReferenceException : Object reference not set to an instance of an object

getting runtime exception System.NullReferenceException : Object reference not set to an instance of an object error when running the code for writing a string in google text box the code is

using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Firefox;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium.Support.PageObjects;

namespace ToolsQA
{

class NUnitTest
{
[FindsBy(How = How.CssSelector, Using = "input[name='q']")][CacheLookup]
public IWebElement serchBox { get; set; }

string url = "https://www.google.com";
IWebDriver driver;
[Test]
public void TestScript()
{
driver = new ChromeDriver(@"C:\ChromeDriver");
driver.Navigate().GoToUrl(url);
////// exception at this line //////
serchBox.SendKeys("beyonce");
}

[TearDown]
public void EndTest()
{
driver.Quit();
}
}
}

Answer

you first have to initialize the object of the page element class , then only it can refrain from null values

PageElements elements = new PageElements();
PageFactory.InitElements(driver, elements);