Object reference not set to an instance of an obje

2019-07-03 09:00发布

问题:

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/");
    }
  }
}

回答1:

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:

public class class2
{
   IWebDriver driver = null;


   public class2(IWebDriver driver)
   {
      this.driver = driver;
   }
   public void method()
   {
     driver.Navigate().GoToUrl("http://www.yahoo.com/");
   }
}

and then your other class would look like this

public void test1()
 {
    driver = new FirefoxDriver();
    class2 obj = new class2(driver);

    driver.Navigate().GoToUrl("http://www.google.com/");
    obj.method();
 }


回答2:

Look at your code:

public class class2
{
    IWebDriver driver = null;
    public void method()
    {
        driver.Navigate().GoToUrl("http://www.yahoo.com/");
    }
}

Of course you're getting a NullReferenceException - driver is always null.

It's not clear what you expected to happen here - but perhaps you meant to pass the FirefoxDriver you instantiate in test1 into method via a parameter?



回答3:

You're assigning the driver in your Class1, so when it tries to navigate on class2's method it fails, as class2's driver is null. 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:

  public class class2
  {
    public void method(IWebDriver driver)
    {
        driver.Navigate().GoToUrl("http://www.yahoo.com/");
    }
  }

and where you call the method in Class1:

    obj.method(driver);


回答4:

You need to pass the reference of driver in Class1 to Class2 and assign it to the driver in there. When you pass by reference, you pass the memory address so the driver in Class2 becomes the same driver in Class1 because they both point to the same address in computer memory.

To pass the driver by reference in Class1 you need below;

obj.method(driver);

You need to modify Class2 so it can receive an IWebDriver in method().