Nothing happend after running test in C# NUnit - c#

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.

Related

Cant Launch a window with Selenium Chrome Driver c#

Environment:
Vs2019, C#
NuGet Package: Selenium v3.141.0 by Selenium Committee.
Chrome Driver from Selenium website - v92.0
IWebDriver Driver = new ChromeDriver("FolderPath"); //time out error here.
Driver.url = "www.google.com"
with no other code, I can't get pass declaring Chrome Driver. I get a time out error with local host.
I tried:
setting a different port.
adding "no-sandbox" to arguments.
I would try utilizing the ChromeDriver NuGet package instead of pointing to a local file location
https://www.nuget.org/packages/Selenium.WebDriver.ChromeDriver/
Here is a simple example for you to reference
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
namespace ExampleDemo
{
[TestFixture]
public class Chrome_test
{
private IWebDriver driver;
[Test(Description="Go To Google")]
public void GoToGoogle() {
homeURL = https://www.google.com/;
driver.Navigate().GoToUrl(homeURL);
}
[TearDown]
public void TearDownTest()
{
driver.Close();
}
[SetUp]
public void SetupTest()
{
driver = new ChromeDriver();
}
}
}
I need to add a chrome option:
ChromeOptions options = new ChromeOptions()
options.add("--remote-debugging-port=9222 ") // change port if necessary

Run Selenium Grid C# Project in Visual Studio

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

Cross-Browser testing with Selenium WebDriver using C#

I would like to be able to run my unit tests across different browsers (FF/IE/Chrome) without having to modify the code to change what webdriver I am using. I am new to selenium testing and would appreciate any recommendations.
I would like to be able to do the following:
run a particular test against a particular browser
run all tests against a particular browser
run all tests against all browsers
Here are some options I have considered but they don't meet my all my needs.
Ask the user (via a Dialog window) which browser to run the test
against
This approach meets condition #1 listed above but not 2 and 3.
This approach would cause the user to be prompted for each test so it does not meet condition #2
Store the default browser in a config file.
The config file can be easily edited with a text editor
This approach meets condition #1 and #2 but requires manually editing
the config file before running the tests.
Here is one easy solution for your problem.
You can use NUnit to execute selenium tests on multiple browsers. All you need to do is download Nunit from NuGet and reference it in your project. Here is a sample code which works just fine.
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.IE;
using OpenQA.Selenium.Chrome;
namespace MultipleBrowserTesting
{
[TestFixture(typeof(FirefoxDriver))]
[TestFixture(typeof(ChromeDriver))]
[TestFixture(typeof(InternetExplorerDriver))]
public class BlogTest<TWebDriver> where TWebDriver : IWebDriver, new()
{
private IWebDriver _driver;
[Test]
public void Can_Visit_Google()
{
_driver = new TWebDriver();
// Navigate
_driver.Manage().Window.Maximize();
_driver.Navigate().GoToUrl("http://www.google.com/");
}
[TestFixtureTearDown]
public void FixtureTearDown()
{
if (_driver != null)
_driver.Close();
}
}
}
If you are using Visual Studio, you can make use of ordered tests. What I did, I have created three separate test cases namely SetIE, SetChrome and SetFireFox.
[TestMethod]
public void SetIE()
{
Browser.Type = "IE";
}
[TestMethod]
public void SetFireFox()
{
Browser.Type = "FF";
}
[TestMethod]
public void SetChrome()
{
Browser.Type = "CR";
}
These methods just set a string in a class variable and do nothing else.
Create a method to initialize your webDriver
IWebDriver WebDriver = null;
public static void InitializeDriver(TestContext t)
{
if (WebDriver == null)
{
string DRIVER_PATH = #"C:\automation\driversFolder\";
switch (Browser.Type)
{
case "IE":
WebDriver = new InternetExplorerDriver(DRIVER_PATH);
break;
case "FF":
WebDriver = new FirefoxDriver();
break;
case "CR":
WebDriver = new ChromeDriver(DRIVER_PATH);
break;
default:
WebDriver = new FirefoxDriver();
break;
}
}
}
See this blog post which more or less describes this solution.
Now what you have to do is to create an ordered test for IE. Put the first test case SetIE there. and below that put your other test case like login etc. Now you have one suite ready to execute your test cases in IE. Similary create ordered tests for Chrome and FireFox. After that , create a fourth orderedtest named "All Browsers". Inside it ,place all of your 3 ordered tests.
After that , here is what you can do now.
A) If you want to run a single test case against a specific browser, just change the browser name in your class and run that test case.
B) if you want to run all test against a particular browser, just execute the ordered test of that particular broser .
C) If you want to run all tests on all browsers, run your fourth ordered test.
I hope it helps.

Get application directory in both console application and its unit tests

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;

How do I use Selenium in C#?

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();
}
}
}

Categories

Resources