I am creating a new Selenium framework using C#. Build is ok but tests failed due to the following error.
TearDown failed for test fixture Account.AddBankAccountFeature
BoDi.ObjectContainerException : Interface cannot be resolved:
TechTalk.SpecFlow.UnitTestProvider.IUnitTestRuntimeProvider('nunit')
TearDown : System.NullReferenceException : Object reference not set to
an instance of an object.
Here is my cs file
using System;
using TechTalk.SpecFlow;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using NUnit.Framework;
namespace Account
{
[Binding]
public class AddBankAccountSteps
{
IWebDriver driver = new ChromeDriver();
[Given(#"User is at the Login Page")]
public void GivenUserIsAtTheLoginPage()
{
driver.Url = "https://go.xxx.com/";
driver.Navigate().GoToUrl(driver.Url);
}
[When(#"User enter UserName and Password")]
public void WhenUserEnterUserNameAndPassword()
{
driver.FindElement(By.Id("email")).SendKeys("aa#ss.com");
driver.FindElement(By.Id("password")).SendKeys("aaa");
}
[When(#"User click on the LogIn button")]
public void WhenUserClickOnTheLogInButton()
{
driver.FindElement(By.Id("submitButton")).Click();
}
[Then(#"User can login in ")]
public void ThenUserCanLoginIn()
{
var expectedURL = "https://go.xxx.com/Dashboard/default.aspx";
var actualURL = driver.Url;
Assert.AreEqual(expectedURL, actualURL);
}
}
}
Thank you.
Related
It gives me this error of the chromedriver.exe does not exists after using the selenium packages. Please let me know what is the issue. I have also followed the instructions as told in the dialog box, but the issue persists! Below are some images of my c# code and G1ANT Studio.
C# Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using G1ANT.Language;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Firefox;
namespace G1ANT.Addon.YouTube
{
[Command(Name = "youtube.open", Tooltip = "It opens youtube in a web browser")]
class OpenCommand : Command
{
public OpenCommand(AbstractScripter scripter) : base(scripter)
{
}
public class Arguments : CommandArguments
{
[Argument(Name = "browser", Required = true, Tooltip = "Type of browser; For Chrome, type: chrome; For Firefox, type: firefox")]
public TextStructure Browser { get; set; } = new TextStructure();
}
public void Execute(Arguments argument)
{
if(argument.Browser.Value == "chrome")
{
IWebDriver driver = new ChromeDriver("C:/Users/Krishna/source/repos/G1ANT.Addon.YouTube/packages/Selenium.Chrome.WebDriver.83.0.0/driver/chromedriver");
driver.Navigate().GoToUrl(#"https://www.youtube.com/");
}
else if(argument.Browser.Value == "firefox")
{
IWebDriver driver = new FirefoxDriver("C:/Users/Krishna/source/repos/G1ANT.Addon.YouTube/packages/Selenium.Firefox.WebDriver.0.26.0/driver/geckodriver");
driver.Navigate().GoToUrl(#"https://www.youtube.com/");
}
else
{
RobotMessageBox.Show("Wrong input" + argument.Browser.Value + "\n For Chrome, type: chrome; For Firefox, type: firefox");
}
}
}
}
Error in G1ANT Studio:
It says the chromedriver.exe does not exist after I run the "youtube.open browser chrome" command in the G1ANT Studio
The answer at this link, was one of, which helped in solving this error!
https://stackoverflow.com/a/51608925/13725510
Secondly, I modified the path, please refer to the code in the question and the following code(Error-solved), the line where path is mentioned:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using G1ANT.Language;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Firefox;
namespace G1ANT.Addon.YouTube
{
[Command(Name = "youtube.open", Tooltip = "It opens youtube in a web browser")]
class OpenCommand : Command
{
public OpenCommand(AbstractScripter scripter) : base(scripter)
{
}
public class Arguments : CommandArguments
{
[Argument(Name = "browser", Required = true, Tooltip = "Type of browser; For Chrome, type: chrome; For Firefox, type: firefox")]
public TextStructure Browser { get; set; } = new TextStructure();
}
public void Execute(Arguments argument)
{
if(argument.Browser.Value == "chrome")
{
IWebDriver driver = new ChromeDriver("C:/Users/Krishna/source/repos/G1ANT.Addon.YouTube/packages/Selenium.Chrome.WebDriver.83.0.0/driver");
driver.Navigate().GoToUrl(#"https://www.youtube.com/");
}
else if(argument.Browser.Value == "firefox")
{
IWebDriver driver = new FirefoxDriver("C:/Users/Krishna/source/repos/G1ANT.Addon.YouTube/packages/Selenium.Firefox.WebDriver.0.26.0/driver");
driver.Navigate().GoToUrl(#"https://www.youtube.com/");
}
else
{
RobotMessageBox.Show("Wrong input: " + argument.Browser.Value + "\n For Chrome, type: chrome; For Firefox, type: firefox");
}
}
}
}
I am creating a new framework as PageFactory has been deprecated.
I am getting the error
BoDi.ObjectContainerException : Interface cannot be resolved: OpenQA.Selenium.IWebDriver (resolution path: UnitTestProject1.Base)
TearDown : BoDi.ObjectContainerException : Interface cannot be resolved: OpenQA.Selenium.IWebDriver (resolution path: UnitTestProject1.Base)
My code snippet of my framework is below. I am not sure how I can resolve this. I am aware I could use Context Injection but am not sure what attributes from my framework I should move and to where.
I was thinking should I move the IWedriver Driver to a class and call this in a constructor but not sure where I should call it in the steps file.
Some help to resolve this issue appreciated, thanks.
using System;
using System.Collections.Generic;
using System.Text;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using SeleniumExtras.PageObjects;
namespace UnitTestProject1
{
public class Base : SpecflowBaseTest
{
protected IWebDriver driver { get; set; }
public Base(IWebDriver Driver)
{
driver = Driver;
//PageFactory.InitElements(Driver, this);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TechTalk.SpecFlow;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using UnitTestProject1.Page;
using OpenQA.Selenium.Remote;
using BoDi;
namespace UnitTestProject1
{
[Binding]
public class SpecflowBaseTest : TechTalk.SpecFlow.Steps
{
// For additional details on SpecFlow hooks see
http://go.specflow.org/doc-hooks
protected IWebDriver Driver { get; set; }
private readonly IObjectContainer objectContainer;
[BeforeScenario]
public void BeforeScenario()
{
Driver = new ChromeDriver();
//this.objectContainer = objectContainer;
//ObjectContainer.RegisterInstanceAs<IWebDriver>(Driver);
Driver.Manage().Window.Maximize();
}
[AfterScenario]
public void AfterScenario()
{
Driver.Close();
Driver.Quit();
}
public void NavigateToURL(string URL)
{
Driver.Navigate().GoToUrl(URL);
}
protected LoginPage LoginPage => new LoginPage(Driver);
}
}
using NUnit.Framework;
using System;
using TechTalk.SpecFlow;
namespace UnitTestProject1.Steps
{
[Binding, Parallelizable]
public class LoginSteps : SpecflowBaseTest
{
[Given(#"I navigate to (.*)")]
public void GivenINavigateToHttpsCompany_Com(string URL)
{
NavigateToURL(URL);
}
[Given(#"I enter bw_(.*) and (.*)")]
public void GivenIEnterBw_Valid_UserAnd(string Username, string
Password)
{
LoginPage.Login(Username, Password);
}
[Then(#"I am logged in as bw_valid_user")]
public void ThenIAmLoggedInAsBw_Valid_User()
{
//LoginPage.
}
}
}
You need to initialize a new IWebDriver object and register it with SpecFlow's dependency injection framework in a [BeforeScenario].
[Binding]
public class SeleniumSpecFlowHooks
{
private readonly IObjectContainer container;
public SeleniumSpecFlowHooks(IObjectContainer container)
{
this.container = container;
}
[BeforeScenario]
public void CreateWebDriver()
{
// Create and configure a concrete instance of IWebDriver
IWebDriver driver = new FirefoxDriver(...)
{
...
};
// Make this instance available to all other step definitions
container.RegisterInstance(driver);
}
[AfterScenario]
public void DestroyWebDriver()
{
IWebDriver driver = container.Resolve<IWebDriver>();
driver.Close();
driver.Dispose();
}
}
Your step definition classes should not be initializing the web driver. Just declare an IWebDriver argument in their constructors.
Base class:
[Binding]
public class SpecflowBaseTest : TechTalk.SpecFlow.Steps
{
protected IWebDriver Driver { get; }
protected LoginPage LoginPage { get; }
public SpecflowBaseTest(IWebDriver driver)
{
Driver = driver;
LoginPage = new LoginPage(driver);
}
public void NavigateToURL(string URL)
{
Driver.Navigate().GoToUrl(URL);
}
}
Child class:
[Binding, Parallelizable]
public class LoginSteps : SpecflowBaseTest
{
[Given(#"I navigate to (.*)")]
public void GivenINavigateToHttpsCompany_Com(string URL)
{
NavigateToURL(URL);
}
[Given(#"I enter bw_(.*) and (.*)")]
public void GivenIEnterBw_Valid_UserAnd(string Username, string Password)
{
LoginPage.Login(Username, Password);
}
[Then(#"I am logged in as bw_valid_user")]
public void ThenIAmLoggedInAsBw_Valid_User()
{
//LoginPage.
}
}
solved by creating a new class
using BoDi;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using TechTalk.SpecFlow;
namespace DoclerQAtests
{
[Binding]
public class WebDriverSupport
{
private readonly IObjectContainer objectContainer;
private ChromeDriver webdriver;
public WebDriverSupport(IObjectContainer objectContainer)
{
this.objectContainer = objectContainer;
}
[BeforeScenario]
public void InitializeWebDriver()
{
this.webdriver = new ChromeDriver();
objectContainer.RegisterInstanceAs<IWebDriver>(webdriver);
}
}
}
For me this issue was resolved by adding a class level field public IWebDriver Driver instead of a local method level driver.
[Binding]
public class DriverSetup
{
private IObjectContainer _objectContainer;
public IWebDriver Driver;
public DriverSetup(IObjectContainer objectContainer)
{
_objectContainer = objectContainer;
}
[BeforeScenario]
public void BeforeScenario()
{
//TODO please supply your Sauce Labs user name in an environment variable
var sauceUserName = Environment.GetEnvironmentVariable("SAUCE_USERNAME", EnvironmentVariableTarget.User);
//TODO please supply your own Sauce Labs access Key in an environment variable
var sauceAccessKey = Environment.GetEnvironmentVariable("SAUCE_ACCESS_KEY", EnvironmentVariableTarget.User);
var sauceOptions = new Dictionary<string, object>
{
["username"] = sauceUserName,
["accessKey"] = sauceAccessKey
};
var chromeOptions = new ChromeOptions
{
BrowserVersion = "latest",
PlatformName = "Windows 10"
};
chromeOptions.AddAdditionalOption("sauce:options", sauceOptions);
Driver = new RemoteWebDriver(new Uri("https://ondemand.saucelabs.com/wd/hub"),
chromeOptions.ToCapabilities(), TimeSpan.FromSeconds(30));
_objectContainer.RegisterInstanceAs(Driver);
}
}
I am trying to do some selenium tests on my new unit test project:
My code is:
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.IE;
using OpenQA.Selenium.Remote;
using OpenQA.Selenium.PhantomJS;
using System;
namespace HelloWorldDevOpsUnitTests
{
[TestClass]
public class ChucksClass1
{
private string baseURL = "http://localhost:5000/";
private RemoteWebDriver driver;
private string browser;
public TestContext TestContext { get; set; }
[TestMethod]
[TestCategory("Selenium")]
[Priority(1)]
[Owner("FireFox")]
public void TireSearch_Any()
{
driver = new FirefoxDriver(new FirefoxBinary(#"C:\Program Files\Mozilla Firefox\Firefox.exe"), new FirefoxProfile(), TimeSpan.FromMinutes(10));
driver.Manage().Window.Maximize();
driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(30));
driver.Navigate().GoToUrl(this.baseURL);
driver.FindElementById("search - box").Clear();
driver.FindElementById("search - box").SendKeys("tire");
//do other Selenium things here!
}
[TestCleanup()]
public void MyTestCleanup()
{
driver.Quit();
}
[TestInitialize()]
public void MyTestInitialize()
{
}
}
}
I got these errors when running:
Message: Test method
HelloWorldDevOpsUnitTests.ChucksClass1.TireSearch_Any threw exception:
OpenQA.Selenium.WebDriverException: Cannot find a file named
'C:\Users\valencil\DevOpsTest\HelloWorldDevOpsUnitTests\bin\Debug\webdriver.json'
or an embedded resource with the id 'WebDriver.FirefoxPreferences'.
TestCleanup method
HelloWorldDevOpsUnitTests.ChucksClass1.MyTestCleanup threw exception.
System.NullReferenceException: System.NullReferenceException: Object
reference not set to an instance of an object..
When you build your project, the Selenium web driver binary should be copied to the output directory of your test project (e.g. /bin/Debug/netcoreapp2.0/). Try passing in the relative path to this binary to the XDriver constructor:
IWebDriver driver;
switch (browser.ToLower())
{
case "firefox":
driver = new FirefoxDriver("./");
break;
case "chrome":
driver = new ChromeDriver("./");
break;
case "ie":
case "internetexplorer":
driver = new InternetExplorerDriver("./");
break;
case "phantomjs":
driver = new PhantomJSDriver("./");
break;
default:
driver = new PhantomJSDriver("./");
break;
}
I am trying out ExtentReports in Visual Studio C#. When i run a test case the html report file is not being generated. I am not sure what is wrong in my code.
I think the path to my reports folder is correct.
In Solution Explorer I created a folder called "Reports" and I would like the report file to be created here.
My code snippet is:
using NUnit.Framework;
using RelevantCodes.ExtentReports;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ExtentReportsDemo
{
[TestFixture]
public class BasicReport
{
public ExtentReports extent;
public ExtentTest test;
[OneTimeSetUp]
public void StartReport()
{
string pth = System.Reflection.Assembly.GetCallingAssembly().CodeBase;
string actualPath = pth.Substring(0, pth.LastIndexOf("bin"));
string projectPath = new Uri(actualPath).LocalPath; // project path of your solution
string reportPath = projectPath + "Reports\\testreport.html";
// true if you want to append data to the report. Replace existing report with new report. False to create new report each time
extent = new ExtentReports(reportPath, false);
extent.AddSystemInfo("Host Name", "localhost")
.AddSystemInfo("Environment", "QA")
.AddSystemInfo("User Name", "testUser");
extent.LoadConfig(projectPath + "extent-config.xml");
}
[Test]
public void DemoReportPass()
{
test = extent.StartTest("DemoReportPass");
Assert.IsTrue(true);
test.Log(LogStatus.Pass, "Assert Pass as consition is true");
}
[Test]
public void DemoReportFail()
{
test = extent.StartTest("DemoReportPass");
Assert.IsTrue(false);
test.Log(LogStatus.Fail, "Assert Pass as condition is false");
}
[TearDown]
public void GetResult()
{
var status = TestContext.CurrentContext.Result.Outcome.Status;
var stackTrace = "<pre>"+TestContext.CurrentContext.Result.StackTrace+"</pre>";
var errorMessage = TestContext.CurrentContext.Result.Message;
if (status == NUnit.Framework.Interfaces.TestStatus.Failed)
{
test.Log(LogStatus.Fail, stackTrace + errorMessage);
}
extent.EndTest(test);
}
[OneTimeTearDown]
public void EndReport()
{
extent.Flush();
extent.Close();
}
}
}
There are no errors when I build the solution. The test runs fine but the testreport.html is not being generated.
I have used NuGet to install extentReports and installed Nunit.
Thanks, Riaz
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using RelevantCodes.ExtentReports;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.IE;
using NUnit.Framework;
using NUnit.Framework.Interfaces;
namespace testingExtentReports
{
[TestClass]
public class UnitTest1
{
public ExtentReports extent;
public ExtentTest test;
IWebDriver driver;
[SetUp]
public void StartReport()
{
string reportPath = #"D:\\TestReport.html";
extent = new ExtentReports(reportPath, true);
extent.AddSystemInfo("Host Name", "Your Host Name")
.AddSystemInfo("Environment", "YourQAEnvironment")
.AddSystemInfo("Username", "Your User Name");
string xmlPath = #"D:\\ExtentConfig.xml";
extent.LoadConfig(xmlPath);
}
[Test]
public void OpenTest1()
{
test = extent.StartTest("OpenTest1", "test Started");
test.Log(LogStatus.Pass, "Website is open properly");
test.Log(LogStatus.Pass, "Successfully Login into agency Portal");
test.Log(LogStatus.Info, "Click on UI button link");
test.Log(LogStatus.Fail, "Error Occurred while creating document");
test.Log(LogStatus.Pass, "Task Released Succssfully");
test.Log(LogStatus.Warning, "Workflow saved with warning");
test.Log(LogStatus.Error, "Error occurred while releasing task.");
test.Log(LogStatus.Unknown, "Dont know what is happning.");
test.Log(LogStatus.Fatal, "Unhandled exception occured.");
extent.EndTest(test);
extent.Flush();
extent.Close();
}
}
}
You just need to Put the ExtentConfig.xml file to your specific folder, TestReport.html automatically generated on a specific path.Copy xml from given link extentReports.xml
I'm learning Selenium/Webdriver NUnit testing and run into a problem when executing a test:
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using NUnit.Framework;
class NUnitTest
{
IWebDriver driver;
FirefoxOptions options;
[SetUp]
public void Initialize()
{
driver = new FirefoxDriver();
}
[Test]
public void OpenAppTest()
{
driver.Navigate().GoToUrl("http:/www.demoqa.com");
}
[TearDown]
public void EndTEst()
{
driver.Quit();
}
}
When running test, I'm getting an exception:
OpenQA.Selenium.WebDriverException: Cannot start the driver service on
localhost TearDown: System.NUllReferenceException: Object reference
not set to an instance of an object
I have no clue how to fix it.
However, the following approach works:
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using Microsoft.VisualStudio.TestTools.UnitTesting;
public class UnitTest1
{
IWebDriver driver;
[TestMethod]
public void VerifyTitle()
{
//Write Actual Test
string title = driver.Title;
Assert.AreEqual(title, "Demoqa | Just another WordPress site");
}
[TestInitialize]
public void Setup()
{
//start browser and open url
driver = new FirefoxDriver();
driver.Navigate().GoToUrl("http:/www.demoqa.com");
}
[TestCleanup]
public void CleanupTest()
{
//close browser
driver.Quit();
}
}
Here, I'm using the same approach to start the webdriver as in the failing example.
The only difference is that the failing example is using NUnit.Framework and the correct one is using Microsoft.VisualStudio.TestTools.UnitTesting
I'm not sure what is wrong with the second approach?