I'm implemented Nunit selenium C# testing in visual studio (Console Application n Class Library). My project in visual studio is console application. I started the selenium grid using
java -Dwebdriver.gecko.driver="..\jar\geckodriver.exe" -Dwebdriver.chrome.driver="..\jar\chromedriver.exe" -Dwebdriver.ie.driver="..\jar\IEDriverServer.exe" -jar ..\jar\selenium-server-standalone-3.14.0.jar -role hub -port 4444
Code:
using Automation_Framework.Manager;
using NUnit.Framework;
using OpenQA.Selenium;
using System;
using System.Collections.Generic;
using System.Text;
namespace Automation_Framework.TestManager
{
[TestFixture]
class ChromeTestManager
{
private WebDriverManager webDriverManager;
private IWebDriver driver;
public ChromeTestManager()
{
webDriverManager = new WebDriverManager();
}
[SetUp]
public void setup()
{
webDriverManager.createDriver("chrome");
driver = webDriverManager.getDriver();
}
[Test]
public void test()
{
driver.Url = "http://www.google.com.my";
driver.Navigate();
}
[TearDown]
public void shutdown()
{
driver.Close();
}
}
}
I had tried execute using Test Explorer but it does not open any browser. I"m following this tutorial.
Questions:
How to run the project with browser open and see all actions?
How to run using Nunit-console-runner.
Please help me. Thanks.
I assume that:
1. You have tried your code locally and your test is opening the browser when you run it on your machine without the grid.
2. Your nodes are set up and registered with the hub.
You need to:
1. Use RemoteWebDriver:
var uri = 'uri_to_your_grid_hub';
var capabilities = new ChromeOptions().ToCapabilities();
var commandTimeout = TimeSpan.FromMinutes(5);
var driver = new RemoteWebDriver(new Uri(uri),capabilities,commandTimeout)
Add the attribute to a class: [Parallelizable(ParallelScope.Self)] in order to run your tests in parallel with other test classes.
In order to verify whether the hub is running, open the browser and navigate to http://localhost:4444 on the hub machine.
Sources:
How can I run NUnit(Selenium Grid) tests in parallel?
Selenium Grid in C#
Useful C# WebDriver examples
Selenium Grid set up
I haven't used grid in .Net but here my answer:
your command is just register a hub, which needs to keep running (open a browser and test it is working)
you need to register your nodes under that hub (different ports) (open a browser and test it is working)
in your code, you should use "RemoteWebDriver" to connect to the hub.
something along these lines (it is in java but I hope it gives you a starting point)
public class Gmail
{
public WebDriver driver=null;
#Parameters("browser") //testng.xml
#Test()
public void GmailTest(String browser)
{
System.out.println("Gmail " + browser);
// RemoteWebdriver
DesiredCapabilities cap = null;
if(browser.equals("firefox")){
cap = DesiredCapabilities.firefox();
cap.setBrowserName("firefox");
cap.setPlatform(Platform.ANY);
}else if (browser.equals("iexplore")){
cap = DesiredCapabilities.internetExplorer();
cap.setBrowserName("iexplore");
cap.setPlatform(Platform.WINDOWS);
}
driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"),cap);
driver.get("http://gmail.com");
driver.findElement(By.id("Email")).sendKeys("abcd");
driver.quit();
}
I hope this helps.good luck
at the beginning I want to tell you I'm new in C# automation testing.
I created NUnit Test Project (.NET Core) and I have problem with running test in C# NUnit. When I click on "Run selected test" in Test Explorer then nothing happens. I don't have any error in my Test Explorer. In output I have error System.ArgumentException: Illegal characters in path.
Additionally when I try to run test from commandline ("C:\Tools\NUnit\bin\net35\nunit3-console.exe" C:\Users\MY_USER\source\repos\NUnitTestProject2\NUnitTestProject2.sln) I have
Could not load file or assembly nunit.framework error.
The only way to run the test is commandline and
dotnet test C:\Users\MY_USER\source\repos\NUnitTestProject2\NUnitTestProject2\NUnitTestProject2.csproj
My NuGet Dependencies:
Microsoft.NET.Test.Sdk(15.5.0)
NUnit (3.9.0)
NUnit3TestAdapter (3.9.0)
Selenium.WebDriver (3.141.0)
All the time my Test Explorer looks like this:
I tried to change version of my NuGet dependencies.
public class Tests
{
IWebDriver driver;
[SetUp]
public void Setup()
{
driver = new ChromeDriver("C:/Users/MY_USER/source/repos/NUnitTestProject1/NUnitTestProject1/bin/Debug/netcoreapp2.1/");
}
[Test]
public void Test1()
{
driver.Navigate().GoToUrl("https://google.com/");
}
}
I would implement a StartChromeDriver() method to handle starting ChromeDriver correctly. Here's an example:
public IWebDriver StartChromeDriver()
{
var options = new ChromeOptions();
options.AddArgument("--disable-extensions");
options.AddArguments("disable-infobars");
options.AddArgument("--no-sandbox")
driver = new ChromeDriver(options);
return driver;
}
Then replace the driver = new ChromeDriver call in your [SetUp] method with driver = StartChromeDriver().
The issue may be that you are not providing any ChromeOptions() when initializing your ChromeDriver instance.
Also, as recommended by another user, I would write a simple test to isolate the issue from Selenium vs. NUnit. You can do so like this:
public class Tests
{
// comment out setup method so this Selenium code does not get run.
// IWebDriver driver;
// [SetUp]
// public void Setup()
// {
// driver = new //ChromeDriver("C:/Users/MY_USER/source/repos/NUnitTestProject1/NUnitTestProject1/bin/Debug/netcoreapp2.1/");
// }
[Test]
public void Test1()
{
Assert.Pass("Passed first test successfully.");
}
}
If your test successfully runs without the Selenium / ChromeDriver code, then you know the issue is with Selenium and not NUnit.
I'm writing GUI tests for an ASP.NET web application but Selenium can not seem to connect to the localhost. Every time I run the test case it loads the chrome browser, but I get the error "ERR_CONNECTION_REFUSED". I can connect to the localhost just fine for development, just not testing.
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
namespace MyApplication.Tests
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void ButtonMenuDimensions_Chrome()
{
try
{
String url = "http://localhost:52956";
ChromeDriver driver = new ChromeDriver();
driver.Navigate().GoToUrl(url);
driver.Manage().Window.Maximize();
String actualHeight = driver.FindElement(By.Id("menu")).GetCssValue("height");
Console.WriteLine("Actual Height: " + actualHeight);
String expectedHeight = "450px";
String actualWidth = driver.FindElement(By.Id("menu")).GetCssValue("width");
String expectedWidth = "200px";
Assert.AreEqual(expectedHeight, actualHeight);
Assert.AreEqual(expectedWidth, actualWidth);
driver.Close();
driver.Dispose();
}
catch
{
Console.WriteLine("Error executing test case: Dimensions");
}
}
}
}
When I open up the output for this test case I am getting
Error executing test case: Dimensions
I suspect you're running the app on iis express, you will need to make sure this is running when your test are by having the ASP website running/debugging in VS.
If you hit the URL http://localhost:52956 without running the ASP website can you still hit it?
I have a console application project with NUnit tests in the same project.
I have been trying to apply this solution.
At run-time the solution worked OK. But when I ran the tests by Resharper test runner or NUnit GUI runner, GetExecutingAssembly().Location returned a path like this: d:\Temp\f4ctjcmr.ofr\nojeuppd.fmf\R2Nbs\assembly\dl3\9766f38e\b9496fb3_43cccf01\.
Disabling shadow-copying fixed the problem in both test runners, but new problems appeared (VS is not able to build the project until NUnit Gui is closed). Is there a better solution than disabling shadow-copying?
Update: Environment.GetCommandLineArgs()[0] returned C:\Program Files (x86)\NUnit 2.6.3\bin\ in the tests running in NUnit Gui with shadow-copying enabled.
Alright, this goes into fun territory.
You should be mocking out this dependency.
Example code:
public interface IApplicationRootService {
Uri GetApplicationRoot();
}
public class ApplicationRootService : IApplicationRootService {
public Uri GetApplicationRoot() {
//etc
}
}
Now, apply liberally to your code where you're calling getexecutingassembly and whatnot. Inject the IApplicationRootService as a constructor dependency.
Ex:
public class DoWork {
private IApplicationRootService _applicationRootService;
public DoWork(IApplicationRootService applicationRootService) {
_applicationRootService = applicationRootService;
}
public void DoSomething() {
var appRoot = _applicationRooService.GetApplicationRoot();
//do your stuff
}
}
Now when you're testing, use a mocking service and mock out the return value of application root to the appropriate folder for nunit to go sniffin'.
Ex code, using nunit and moq:
[Test]
public static void test_do_something() {
var applicationRootService = new Mock<IApplicationRootService>();
applicationRootService.Setup(service => service.GetApplicationRoot()).Returns(new Uri("MyRoot", UriKind.Relative);
var myClass = new DoWork(applicationRootService.Object);
//continue testing!
}
The following solution worked for me. Please vote to its author if it helps you.
As explained in the MSDN forums post, How to convert URI path to normal filepath?, I used the following:
// Get normal filepath of this assembly's permanent directory
var path = new Uri(
System.IO.Path.GetDirectoryName(
System.Reflection.Assembly.GetExecutingAssembly().CodeBase)
).LocalPath;
Selenium.
I downloaded the C# client drivers and the IDE. I managed to record some tests and successfully ran them from the IDE. But now I want to do that using C#. I added all relevant DLL files (Firefox) to the project, but I don't have the Selenium class. Some Hello, World! would be nice.
From the Selenium Documentation:
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium;
class GoogleSuggest
{
static void Main(string[] args)
{
IWebDriver driver = new FirefoxDriver();
//Notice navigation is slightly different than the Java version
//This is because 'get' is a keyword in C#
driver.Navigate().GoToUrl("http://www.google.com/");
IWebElement query = driver.FindElement(By.Name("q"));
query.SendKeys("Cheese");
System.Console.WriteLine("Page title is: " + driver.Title);
driver.Quit();
}
}
Install the NuGet packet manager
Download link: https://visualstudiogallery.msdn.microsoft.com/27077b70-9dad-4c64-adcf-c7cf6bc9970c
Create a C# console application
Right-click on the project → Manage NuGet Packages.
Search for "Selenium" and install package Selenium.Support.
You are done now, and you are ready to write your code :)
For code with Internet Explorer, download the Internet Explorer driver.
Link: http://selenium-release.storage.googleapis.com/index.html
Open 2.45 as its the latest release
Download IEDriverServer_x64_2.45.0.zip or IEDriverServer_Win32_2.45.0.zip
Extract and simply paste the .exe file at any location, for example C:\
Remember the path for further use.
Overall reference link: Selenium 2.0 WebDriver with Visual Studio, C#, & IE – Getting Started
My sample code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OpenQA.Selenium;
using OpenQA.Selenium.Support.UI;
using OpenQA.Selenium.IE;
namespace Selenium_HelloWorld
{
class Program
{
static void Main(string[] args)
{
IWebDriver driver = new InternetExplorerDriver("C:\\");
driver.Navigate().GoToUrl("http://108.178.174.137");
driver.Manage().Window.Maximize();
driver.FindElement(By.Id("inputName")).SendKeys("apatra");
driver.FindElement(By.Id("inputPassword")).SendKeys("asd");
driver.FindElement(By.Name("DoLogin")).Click();
string output = driver.FindElement( By.XPath(".//*[#id='tab-general']/div/div[2]/div[1]/div[2]/div/strong")).Text;
if (output != null )
{
Console.WriteLine("Test Passed :) ");
}
else
{
Console.WriteLine("Test Failed");
}
}
}
}
To set up the IDE for Selenium in conjunction with C# is to use Visual Studio Express. And you can use NUnit as the testing framework. The below links provide you more details. It seems you have set up what is explained in the first link. So check the second link for more details on how to create a basic script.
How to setup C#, NUnit and Selenium client drivers on Visual Studio Express for Automated tests
Creating a basic Selenium web driver test case using NUnit and C#
Sample code from the above blog post:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
// Step a
using OpenQA.Selenium;
using OpenQA.Selenium.Support;
using OpenQA.Selenium.Firefox;
using NUnit.Framework;
namespace NUnitSelenium
{
[TestFixture]
public class UnitTest1
{
[SetUp]
public void SetupTest()
{
}
[Test]
public void Test_OpeningHomePage()
{
// Step b - Initiating webdriver
IWebDriver driver = new FirefoxDriver();
// Step c: Making driver to navigate
driver.Navigate().GoToUrl("http://docs.seleniumhq.org/");
// Step d
IWebElement myLink = driver.FindElement(By.LinkText("Download"));
myLink.Click();
// Step e
driver.Quit();
)
}
}
One of the things that I had a hard time finding was how to use PageFactory in C#. Especially for multiple IWebElements. If you wish to use PageFactory, here are a few examples. Source: PageFactory.cs
To declare an HTML WebElement, use this inside the class file.
private const string _ID ="CommonIdinHTML";
[FindsBy(How = How.Id, Using = _ID)]
private IList<IWebElement> _MultipleResultsByID;
private const string _ID2 ="IdOfElement";
[FindsBy(How = How.Id, Using = _ID2)]
private IWebElement _ResultById;
Don't forget to instantiate the page object elements inside the constructor.
public MyClass(){
PageFactory.InitElements(driver, this);
}
Now you can access that element in any of your files or methods. Also, we can take relative paths from those elements if we ever wish to. I prefer pagefactory because:
I don't ever need to call the driver directly using driver.FindElement(By.Id("id"))
The objects are lazy initialized
I use this to write my own wait-for-elements methods, WebElements wrappers to access only what I need to expose to the test scripts, and helps keeps things clean.
This makes life a lot easier if you have dynamic (autogerated) webelements like lists of data. You simply create a wrapper that will take the IWebElements and add methods to find the element you are looking for.
FirefoxDriverService service = FirefoxDriverService.CreateDefaultService(#"D:\DownloadeSampleCode\WordpressAutomation\WordpressAutomation\Selenium", "geckodriver.exe");
service.Port = 64444;
service.FirefoxBinaryPath = #"C:\Program Files (x86)\Mozilla Firefox\firefox.exe";
Instance = new FirefoxDriver(service);
C#
First of all, download Selenium IDE for Firefox from the Selenium IDE.
Use and play around with it, test a scenario, record the steps, and then export it as a C# or Java project as per your requirement.
The code file contains code something like:
using System;
using System.IO;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
// Add this name space to access WebDriverWait
using OpenQA.Selenium.Support.UI;
namespace MyTest
{
[TestClass]
public class MyTest
{
public static IWebDriver Driver = null;
// Use TestInitialize to run code before running each test
[TestInitialize()]
public void MyTestInitialize()
{
try
{
string path = Path.GetFullPath(""); // Copy the Chrome driver to the debug
// folder in the bin or set path accordingly
Driver = new ChromeDriver(path);
}
catch (Exception ex)
{
string error = ex.Message;
}
}
// Use TestCleanup to run code after each test has run
[TestCleanup()]
public void MyCleanup()
{
Driver.Quit();
}
[TestMethod]
public void MyTestMethod()
{
try
{
string url = "http://www.google.com";
Driver.Navigate().GoToUrl(url);
IWait<IWebDriver> wait = new WebDriverWait(Driver, TimeSpan.FromSeconds(30.00)); // Wait in Selenium
wait.Until(ExpectedConditions.PresenceOfAllElementsLocatedBy(By.XPath(#"//*[#id='lst - ib']")));
var txtBox = Driver.FindElement(By.XPath(#"//*[#id='lst - ib']"));
txtBox.SendKeys("Google Office");
var btnSearch = Driver.FindElement(By.XPath("//*[#id='tsf']/div[2]/div[3]/center/input[1]"));
btnSearch.Click();
System.Threading.Thread.Sleep(5000);
}
catch (Exception ex)
{
string error = ex.Message;
}
}
}
}
You need to get the Chrome driver from here.
You need to get NuGet packages and necessary DLL files for the Selenium NuGet website.
You need to understand the basics of Selenium from the Selenium documentation website.
That's all...
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Interactions;
using OpenQA.Selenium.Support.UI;
using SeleniumAutomationFramework.CommonMethods;
using System.Text;
[TestClass]
public class SampleInCSharp
{
public static IWebDriver driver = Browser.CreateWebDriver(BrowserType.chrome);
[TestMethod]
public void SampleMethodCSharp()
{
driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(5));
driver.Url = "http://www.store.demoqa.com";
driver.Manage().Window.Maximize();
driver.FindElement(By.XPath(".//*[#id='account']/a")).Click();
driver.FindElement(By.Id("log")).SendKeys("kalyan");
driver.FindElement(By.Id("pwd")).SendKeys("kalyan");
driver.FindElement(By.Id("login")).Click();
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
IWebElement myDynamicElement = wait.Until<IWebElement>(d => d.FindElement(By.LinkText("Log out")));
Actions builder = new Actions(driver);
builder.MoveToElement(driver.FindElement(By.XPath(".//*[#id='menu-item-33']/a"))).Build().Perform();
driver.FindElement(By.XPath(".//*[#id='menu-item-37']/a")).Click();
driver.FindElement(By.ClassName("wpsc_buy_button")).Click();
driver.FindElement(By.XPath(".//*[#id='fancy_notification_content']/a[1]")).Click();
driver.FindElement(By.Name("quantity")).Clear();
driver.FindElement(By.Name("quantity")).SendKeys("10");
driver.FindElement(By.XPath("//*[#id='checkout_page_container']/div[1]/a/span")).Click();
driver.FindElement(By.ClassName("account_icon")).Click();
driver.FindElement(By.LinkText("Log out")).Click();
driver.Close();
}
}
You will need to install Microsoft Visual Studio community Edition
Create a new project as Test Project of C#
Add Selenium references from the NuGet Package Manager. Then you will be all set.
Create a new class and use [Test Class] and [Test Method] annotations to run your script
You can refer to Run Selenium C# | Setup Selenium and C# | Configure Selenium C# for more details.
Use the below code once you've added all the required C# libraries to the project in the references.
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
namespace SeleniumWithCsharp
{
class Test
{
public IWebDriver driver;
public void openGoogle()
{
// creating Browser Instance
driver = new FirefoxDriver();
//Maximizing the Browser
driver.Manage().Window.Maximize();
// Opening the URL
driver.Navigate().GoToUrl("http://google.com");
driver.FindElement(By.Id("lst-ib")).SendKeys("Hello World");
driver.FindElement(By.Name("btnG")).Click();
}
static void Main()
{
Test test = new Test();
test.openGoogle();
}
}
}