2

我是 C# 的初学者。当我在 NUnit 编程中实例化一个类时,我得到一个空引用异常。我有两个单独的类——一个全局库和主程序。我想在设置和测试中都使用实例化类(globalLib)。异常错误是因为我已将 globalLib 设置为 null。我该如何纠正这个?应该如何实例化该类以便可以在设置和测试中使用它?我已经给出了下面的代码。任何帮助表示赞赏。谢谢。

我的代码:

第一类:

[TestFixture]
public class LandForSale
{
    private IWebDriver driver = null;
    GlobalLibrary globalLib = null;
    [SetUp]
    public void OpenBrowser()
    {
        globalLib = new GlobalLibrary(driver);
        globalLib.StartDriver();           
    }
    [Test]
    public void TestScenario()
    {
        string[] setofitems = { "Residential", "Commercial" };
        foreach (string item in setofitems)
        {
           globalLib.OpenUrl();
           globalLib.Search();
           etc...
        }
    }       
}

}

第 2 类:

public class GlobalLibrary
{
    IWebDriver driver = null;
    public GlobalLibrary(IWebDriver driver)
    {
        this.driver = driver;
    }
    public IWebDriver StartDriver()
    {
        driver = new FirefoxDriver();
        return driver;
    }
    public void OpenUrl()
    {
        driver.Navigate().GoToUrl("http://www.auction.com/");
        driver.Manage().Window.Maximize();
    }
    public void Search()...
}

}

4

2 回答 2

1

NUnit 将[SetUp]在每个标记方法之前运行标记方法[Test]。在您的设置方法中,您将一个空值传递给构造函数。那时您应该传递一个驱动程序:

globalLib = new GlobalLibrary(new SomeDriverClass());

另外,我认为您的 GlobalLibrary 类将受益于更好的构造函数:

public class GlobalLibrary
{
    private IWebDriver driver = null;
    //Constructor with optional parameter allows you to pass in driver of choice
    // OR pass in nothing and get the default Firefox driver 
    public GlobalLibrary(IWebDriver initDriver = null)
    {
        this.driver = initDriver ?? new FirefoxDriver();
    }
    //StartDriver is no longer necessary, but we might want to be able to
    // grab the driver that is being used, so we'll add this read-only property.
    public IWebDriver CurrentDriver  
    {
        get
        {
            return driver;
        }
    }

    //Rest of methods
}
于 2013-08-21T19:43:28.423 回答
0

我在问题区域添加了评论

[TestFixture]
public class LandForSale
{
    private IWebDriver driver = null;
    GlobalLibrary globalLib = null;
    [SetUp]
    public void OpenBrowser()
    {
        globalLib = new GlobalLibrary(driver);
        globalLib.StartDriver();           
    }
    [Test]
    public void TestScenario()
    {
        string[] setofitems = { "Residential", "Commercial" };
        foreach (string item in setofitems)
        {
           globalLib.OpenUrl(); //If the OpenBrowser() method is not called then globalLib is null
           globalLib.Search();
           etc...
        }
    }       
}

我建议添加一个构造函数来实例化你的driverglobalLib字段

于 2013-08-21T19:33:33.217 回答