繁体   English   中英

你调用的对象是空的

[英]Object reference not set to an instance of an object

当我在NUnit中运行这个程序时,我收到一个错误

你调用的对象是空的。

虽然这不是原始程序,但我也遇到了类似的错误。 任何帮助赞赏。 异常发生在

driver.Navigate().GoToUrl("http://www.yahoo.com/");

程序:

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

看看你的代码:

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

当然你得到一个NullReferenceException - driver总是为null

目前还不清楚你期望在这里发生什么 - 但也许你想通过参数将你在test1实例化的FirefoxDriver传递给method

你在Class1分配driver ,所以当它尝试在class2method上导航时,它会失败,因为class2drivernull 在调用任何方法之前,需要为其赋值。

我不知道为什么你希望它因NullReferenceException而失败。

你可能想写的是:

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

并在Class1调用方法:

    obj.method(driver);

如果类中有对象,则需要先实例化才能使用它。 可以说,最好的地方之一是你的构造函数。

像这样:

public class class2
{
   IWebDriver driver = null;


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

然后你的其他课就像这样

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

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

您需要将Class1driver引用传递给Class2并将其分配给那里的driver 通过引用传递时,传递内存地址,以便Class2driver成为Class1的相同driver ,因为它们都指向计算机内存中的相同地址。

要在Class1通过引用传递驱动程序,您需要在下面;

obj.method(driver);

您需要修改Class2以便它可以在method()接收IWebDriver

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM