使用Chrome WebDriver在C#.NET中使用Selenium 3.4.0处理文本案例。我有一个包装器来处理运行测试的浏览器,在执行此操作后,它不会初始化任何一个浏览器。
错误:(来自我的browserfactory文件,意思是driver = null但是显式是从logintext设置的)
Message: System.NullReferenceException : The WebDriver browser instance was not initialized. You should first call the method InitBrowser.
LoginTest.cs:
using NUnit.Framework;
using qa.PageObjects;
using qa.WrapperFactory;
using System.Configuration;
namespace qa.TestCases
{
class LoginTest
{
[Test]
public void Test()
{
// Sign in through google first, so we don't have to follow new tabs
BrowserFactory.InitBrowser( "Chrome" );
BrowserFactory.LoadApplication( ConfigurationManager.AppSettings["URL"] );
Page.Login.ClickOnMyAccount();
Page.Login.LoginToGoogle();
BrowserFactory.CloseAllDrivers();
}
}
}
BrowserFactory.cs:
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Firefox;
using System;
using System.Collections.Generic;
namespace qa.WrapperFactory
{
class BrowserFactory
{
private static readonly IDictionary<string, IWebDriver> Drivers = new Dictionary<string, IWebDriver>();
private static IWebDriver driver;
public static IWebDriver Driver
{
get
{
if ( driver == null )
throw new NullReferenceException( "The WebDriver browser instance was not initialized. You should first call the method InitBrowser." );
return driver;
}
private set
{
driver = value;
}
}
public static void InitBrowser( string browserName )
{
switch ( browserName )
{
case "Firefox":
if ( Driver == null )
{
driver = new FirefoxDriver();
Drivers.Add( "Firefox", Driver );
}
break;
case "Chrome":
if ( Driver == null )
{
driver = new ChromeDriver();
Drivers.Add( "Chrome", Driver );
}
break;
}
}
public static void LoadApplication( string url )
{
Driver.Url = url;
}
public static void CloseAllDrivers()
{
foreach ( var key in Drivers.Keys )
{
Drivers[key].Close();
Drivers[key].Quit();
}
}
}
}
答案 0 :(得分:1)
在初始化驱动程序之前会抛出错误。
在InitBrowser()...
中调用Driver时case "Chrome":
if ( Driver == null )
执行此get语句,私有变量驱动程序为null ...
public static IWebDriver Driver
{
get
{
if ( driver == null )
throw new NullReferenceException( "The WebDriver browser instance was not initialized. You should first call the method InitBrowser." );
return driver;
解决此问题的一种方法是在初始化时检查私有驱动程序变量是否为空。
public static void InitBrowser( string browserName )
{
switch ( browserName )
{
case "Firefox":
if ( driver == null )
{
driver = new FirefoxDriver();
Drivers.Add( "Firefox", Driver );
}
break;
case "Chrome":
if ( driver == null )
{
driver = new ChromeDriver();
Drivers.Add( "Chrome", Driver );
}
break;
}
}