When I run this program in NUnit I get an error
Object reference not set to an instance of an object.
Though this is not the original program I get a similar error there too. Any help appreciated. Exception occurs at
driver.Navigate().GoToUrl("http://www.yahoo.com/");
Program:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium;
namespace Class_and_object
{
[TestFixture]
public class Class1
{
IWebDriver driver = null;
[Test]
public void test1()
{
class2 obj = new class2();
driver = new FirefoxDriver();
driver.Navigate().GoToUrl("http://www.google.com/");
obj.method();
}
}
public class class2
{
IWebDriver driver = null;
public void method()
{
driver.Navigate().GoToUrl("http://www.yahoo.com/");
}
}
}
You're assigning the
driver
in yourClass1
, so when it tries to navigate onclass2
'smethod
it fails, asclass2
'sdriver
isnull
. You need to assign it a value before calling any methods on it.I don't know why you wouldn't expect it to fail with a
NullReferenceException
.What you probably meant to write was:
and where you call the method in
Class1
:Look at your code:
Of course you're getting a
NullReferenceException
-driver
is alwaysnull
.It's not clear what you expected to happen here - but perhaps you meant to pass the
FirefoxDriver
you instantiate intest1
intomethod
via a parameter?If you have an object in a class It needs to be instantiate before you can use it. Arguably one of the best places to do this is in you constructor.
like this:
and then your other class would look like this
You need to pass the reference of
driver
inClass1
toClass2
and assign it to thedriver
in there. When you pass by reference, you pass the memory address so thedriver
inClass2
becomes the samedriver
inClass1
because they both point to the same address in computer memory.To pass the driver by reference in
Class1
you need below;You need to modify
Class2
so it can receive anIWebDriver
inmethod()
.