Warning: fopen(/tmp/SghXTngBZPli-dFZBG0.tmp): failed to open stream: Disk quota exceeded in /home/executea/public_html/blog/wp-admin/includes/class-wp-filesystem-ftpext.php on line 139

Warning: unlink(/tmp/SghXTngBZPli-dFZBG0.tmp): No such file or directory in /home/executea/public_html/blog/wp-admin/includes/class-wp-filesystem-ftpext.php on line 142
Site Loader
Auckland, New Zealand
In this part we will use NUnit framework with Selenium C# in Visual Studio to execute multiple test methods along with many other features like
  • Initializing the Test method – Before execution
  • Cleaning up the Test method — After execution
NUnit will also give us many other assertion features which will be helpful while trying to assert two objects types, some of the methods are shown below

Splitting our code

In this post, we are going to split the code discussed in our last post to three different methods like
  • Initialize() — Setup
  • ExecuteTest() – Test
  • CleanUp – Teardown
Here is the complete explanation of the above discussion in the video Here is the complete code of the above video
class Program
    {
        //Create Global reference for our browser via WebDriver
        IWebDriver driver = new ChromeDriver();

        [SetUp]
        public void Initialize()
        {
            //Navigate to Execute automation demo page
            driver.Navigate().GoToUrl("http://executeautomation.com/demosite/index.html?UserName=&Password=&Login=Login");
            Console.WriteLine("Opened URL");
        }


        [Test]
        public void ExecuteTest()
        {
            //Find the Element
            IWebElement element = driver.FindElement(By.Id("q"));

            //Perform Ops
            element.SendKeys("executeautomation");

            Console.WriteLine("Executed Test");
        }

        [Test]
        public void NextTest()
        {
            Console.WriteLine("Next method");
        }

        [TearDown]
        public void CleanUp()
        {
            driver.Close();
            Console.WriteLine("Closed the browser");
        }
 }
Thanks for watching the video and reading the post!! Please leave your comments and let me know if there is anything need to be improved in the post!!! Thanks, Karthik KK

Post Author: Karthik kk

58 Replies to “Using NUnit with Selenium C#”

  1. First off, thank you for all the videos you have done so far. I have watched all of your Selenium ones to date.

    I wanted to see if you could help me with a problem where I would like to make sure my web browser has focus when the webdriver is running a test on it. Currently if I launch a test and there is already a window up on the desktop, selenium will launch a new window but it never gains focus. I would like to be able to see browser with focus when running the tests without having to click on the window each time. This would also help if I had to take a screenshot during the test when there is a fail.

    Thanks.

    1. Thank you very much for watching all my videos !!!

      There are two important points to note for your question

      1. Currently, Selenium will not support running on existing browser.
      2. Hence, its always wise idea to first close all the existing instance of browser (which runs same application/page)

      But, selenium should get focus on the browser instance which it has launched newly, sometimes it may go wrong (thats in worst case scenario)

      Thanks,
      Karthik KK

  2. I am using Microsoft Visual Studio Express 2013, and the NUnit Test Adapter cannot be found in ‘Extensions and Updates…’. I tried ‘Manage NuGet Packages for Solution’ and installed ‘NUnit Test Adapter for VS2012, VS 2013 and VS 2015’ to get the test adapter. However, when I build the solution, nothing appears in my test explorer. My test settings are on x64 platform and tried cleaning my solution and rebuilding it. Any ideas why my test won’t show in test explorer?

    1. Try it using Package manager console
      Tool –>Library Package manege—>Package manager console
      then Type ” Install -package Nunit-Version 2.6.2″

    2. Same problem happened with me.
      Solution that worked for me
      1)Uninstall everything with name starting with NUnit
      2)Install NUnit3 and NUnit3 test adapter.

      try again, should work fine

  3. Karthik,
    Thanx for your videos. They are very good and quick.
    I have one question. When I executed the above code, its giving me an error that it does not have a main method:
    ‘sample1.exe’ does not contain a static ‘Main’ method suitable for an entry point?

    1. The reason is, NUnit will not have main method, you need to execute the code using Test Explorer and run the specific test method.

      Thanks,
      Karthik KK

      1. Thanks Karthik for the reply. Initially i copied the code you have given here and it gave me an error saying ‘no main method’. After that I entered the code you did in the video, it worked. The code in your video has a main method in it. When I am commenting the main method, it throws error again. I am still curious whether this will work without main method or am I doing anything wrong?

        Also I was expecting a console/ window to come up in the console.writeline();. But it just wrote into the output. So no console come up in nunit?
        I am pasting my code here:( Thanx a lot for your help…)

        using OpenQA.Selenium;
        using OpenQA.Selenium.Chrome;
        using System;
        using System.Collections.Generic;
        using System.Linq;
        using System.Text;
        using NUnit.Framework;
        //using System.Threading.Tasks;

        namespace sample1
        {
        public class Program
        {
        //Create Global reference for our browser via WebDriver
        IWebDriver driver = new ChromeDriver();
        static void Main(string[] args)
        {

        }

        [SetUp]
        public void Initialize()
        {
        //Navigate to Execute automation demo page
        driver.Navigate().GoToUrl(“https://www.google.com”);
        Console.WriteLine(“Opened URL”);

        }

        [Test]
        public void ExecuteTest()
        {
        //Find the Element
        IWebElement element = driver.FindElement(By.Name(“q”));

        //Perform Ops
        element.SendKeys(“execute automation”);

        Console.WriteLine(“Executed Test”);

        }

        //[Test]
        //public void NextTest()
        //{
        // Console.WriteLine(“Next method”);
        //}

        [TearDown]
        public void CleanUp()
        {
        driver.Close();
        Console.WriteLine(“Closed the browser”);
        }

        }
        }

        1. Karthik,
          I did some research. Looks like we need to create a class library, not a console application. Console App needs a main(). Create Nunit test as a class library and execute using test explorer can be the possible solution.

          1. Thanks, a lot Shalini. I created a class library and was able to see my tests in test explorer.

            -Vishal Dewani

  4. Karthik,

    I am looking to use some reporting tool that can be plugged in with selenium webdriver (C#,Nunit). Do you have any tutorial/suggestions that can be used? I have used ExtentReport that that works fine for the most part but looking for other options too

  5. Hello Karthik,

    I am a newbie to Selenium . I was following the steps that you had mentioned in the tutorial.However I am unable to see the tests in the Test Explorer. I tried building the solution ,cleaning,re-building the solution but nothing seems to work.Could you please help me out ?

      1. I also have same issue ,but already add NUnit adapter but in test explore not display any thing ….PLZ reply soon

  6. Hi,

    I have installed everything including Selenium web driver, Chrome driver , Nunit adapter and nunit run also.
    But nothing is shown in my test explorer..

    Please help

  7. I install NUnitTestAdapter in Package manager console but Description provide as in is for VS 2012 ,I think that it is the rezone for not provide the Testcases in test explore ….What is your VS version your using ………..And what is the required Version for VS2013 ….

  8. Hi,
    I am using the same exact code(even copied it) but I unable to see anything on test explorer..Please help..Added all the references but not working..

    namespace SeleniumPOC
    {
    class Program
    {
    //Create reference for Chrome
    IWebDriver driver = new ChromeDriver();

    static void Main(string[] args)
    {
    }

    [SetUp]
    public void Initialize()
    {

    //Navigate to Google page
    driver.Navigate().GoToUrl(“http://google.com”);
    Console.WriteLine(“Opening Google”);

    }

    [Test]
    public void ExecuteTest()
    {
    //find the search text box on page
    IWebElement element = driver.FindElement(By.Name(“q”));

    //Input data
    element.SendKeys(“automation”);

    Console.WriteLine(“Entering data”);

    }
    [TearDown]
    public void CleanUp()
    {
    //close the broswer
    driver.Close();
    Console.WriteLine(“Closing the Broswer”);
    }
    }
    }

  9. Hi,
    I am using the same exact code(even copied it) but I unable to see anything on test explorer..Please help..Added all the references but not working..

    using NUnit.Framework;
    using OpenQA.Selenium;
    using OpenQA.Selenium.Chrome;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    namespace SeleniumPOC
    {
    class Program
    {
    //Create reference for Chrome
    IWebDriver driver = new ChromeDriver();

    static void Main(string[] args)
    {
    }

    [SetUp]
    public void Initialize()
    {

    //Navigate to Google page
    driver.Navigate().GoToUrl(“http://google.com”);
    Console.WriteLine(“Opening Google”);

    }

    [Test]
    public void ExecuteTest()
    {
    //find the search text box on page
    IWebElement element = driver.FindElement(By.Name(“q”));

    //Input data
    element.SendKeys(“automation”);

    Console.WriteLine(“Entering data”);

    }

    [TearDown]
    public void CleanUp()
    {
    //close the broswer
    driver.Close();
    Console.WriteLine(“Closing the Broswer”);
    }

    }
    }

  10. Hi Kritik

    Can u please help me out :-

    class Program
    {
    IWebDriver driver = new ChromeDriver();
    static void Main(string[] args)
    {

    }

    [SetUp]
    public void initialize()
    {
    driver.Navigate().GoToUrl(“www.google.com”);

    }

    [Test]
    public void Execute()
    {
    driver.FindElement(By.Id(“lst-ib”)).SendKeys(“Selenium”);

    }

    [TearDown]
    public void cleanup()
    {
    driver.Close();

    }
    }

    This solution build is showing successful but this test is not running(not showing output). I run this using TEST menu, all test solution.

  11. Hi Karthik,

    Thanks for such clear explanation and wonderful videos.
    I am using Visual studio 2012. I have installed all the above mentioned drivers.
    When i remove main method. i get compilation error. If i add and run, just one command blinks and goes off. I am not able to see any result. Please help me.

    Thanks,
    Suma

    1. I guess, you should try running test from test explorer, instead of running from Debug via visual studio, since its not console application rather its a test application.

      Thanks,
      Karthik KK

  12. Hi Karthik,

    I installed latest Nunit3 Test Adaptor, then it started working.

    Thanks a much.

  13. Hi Karthik..
    I am doing test automation through Selenium with C# lang binding in Visual Studio IDE..I am trying to run a test, which will execute in all the 3 browsers (Chrome, Firefox and IE) simultaneously through window task scheduler. I am using selenium.ITakesScreenshot interface to capture screen shot images of the screen in a specified folder. when I run the scheduler, it takes screen shots for chrome and firefox browsers perfectly but with IE it always produce blank images/screens. could you please help me out here.

  14. Awesome Videos, Thanks! Any advice on CI (specifically Bamboo) and Selenium. We can’t use chrome drive in bamboo with accordion elements. Coming to the conclusion we need to reference an external selenium grid, rather than having selenium nested in code. Any thoughts?

    Thanks!

  15. Hi Karthik,

    Not able to access your youtube tutorials, it says DNS address could not be found, can you please tell or share the link as I think the existing one got expired !!

    1. No such thing, I can still able to access, could you please check connectivity from yourside.

      Thanks,
      Karthik KK

  16. Hi, I have a question. I am using your tutorial for NUnit, but I am runnig on to a problem with my test. It allways fails with this message http://imtp.me/bzin029fh.p problem is not in real test, that works fine, but this time out. If I change end of test do driver.Quit. Test will pass, but it allways take 1 minute, instead of about 10 seconds. Any ideas what is wrong? I am using Selenium 3.0, VS2015 and NUnit 3. Thank you

  17. Hi Karthik,

    I am a novice in Selenium and your videos really helped me a lot in understanding Selenium basics. But while installation I am facing an issue, I am using VS 2013 Professional edition and while installing Nunit, I am able to install “NUnit Templates for Visual Studio” but when I try to find “NUnit3 Test Adapter”, I don’t find any search result. Also, in one of your videos I saw we can install “NUnit Test Adapter” and “NUnit Test Project Template” which I am able to do. If I install just these two, do I need to install “NUnit Templates for Visual Studio” and “NUnit3 Test Adapter”? Please suggest because I am stuck here.

    1. All you need is to install

      1. NUnit 3.x (from Nuget package manager as reference)
      2. NUnit Test Adaptor (from Extensions and updates of Visual studio)

      Hope it helps !

      Thanks,
      Karthik KK

      1. Hey Karthik,

        Thanks a lot for really quick reply. It works now.
        But now I encounter another issue. I am writing a simple program to open the browser window and maximize it. Following is the code:

        namespace SeleniumTest1
        {
        [TestFixture]
        public class UnitTest1
        {
        IWebDriver driver;

        [SetUp]
        public void testSetup()
        {
        driver = new FirefoxDriver();
        driver.Navigate().GoToUrl(“http://google.co.in”);
        }

        [Test]
        public void windowMaximize()
        {
        driver.Manage().Window.Maximize();
        }

        [TearDown]
        public void tearDown()
        {
        driver.Quit();
        }
        }
        }
        And the error message is:
        Result Message:
        OpenQA.Selenium.DriverServiceNotFoundException : The geckodriver.exe file does not exist in the current directory or in a directory on the PATH environment variable. The driver can be downloaded at https://github.com/mozilla/geckodriver/releases.
        TearDown : System.NullReferenceException : Object reference not set to an instance of an object.
        Result StackTrace:
        at OpenQA.Selenium.DriverService.FindDriverServiceExecutable(String executableName, Uri downloadUrl)
        at OpenQA.Selenium.Firefox.FirefoxDriverService.CreateDefaultService()
        at OpenQA.Selenium.Firefox.FirefoxDriver..ctor(FirefoxOptions options)
        at OpenQA.Selenium.Firefox.FirefoxDriver..ctor()
        at SeleniumTest1.UnitTest1.testSetup() in c:\Users\natasha.batra\Source\Repos\WebdriverTest\SeleniumTest1\SeleniumTest1\UnitTest1.cs:line 19
        –TearDown
        at SeleniumTest1.UnitTest1.tearDown() in c:\Users\natasha.batra\Source\Repos\WebdriverTest\SeleniumTest1\SeleniumTest1\UnitTest1.cs:line 32

        Could you please help me with this?

      2. Below code builds successfully, but when I try to run the test it gives me error. And it gives me error for all the browsers not just Firefox.

      3. Hi Karthik,

        Even I also faced the same issue previously, as I was added “NunitTestAdaptor” as a reference instead of downloading that from Tools-> Extensions and updates.
        Now I downloaded from Extensions and updates and is working fine. Thanks for your great answer.

  18. SendKeys is not working for me.
    I have this version of SeleniumWebDriver and Chrome Driver

    It opens up Google, but sendkeys are not working.

    1. Hi Karthik

      SendKeys is not working for me, though it allowed me to Navigate to Google.
      I have used SeleniumWebDriver/ChromeDriver and NUnit as mentioned above.

      Still facing issues. Any help from your side will be much appreciated.

      Thanks

        1. Thanks for a quick reply.
          Its not showing any error, My script opened Google and then searched the element with the name ‘q’ thats the search text box , and then when i send keys i.e. executeautomation , it did not fill in the search box and script stopped without doing that.

          I mean element.SendKeys(“executeautomation”); is not working. Not filling the Google search textbox with the executeautomation while running the script.

          Hope you understand what i mean, if not let me know. I will try my best to explain.

          Your videos are really awesome.

          Thanks

  19. Thank you for all the videos you have done so far.

    I am facing issue while running script in chrome driver and getting
    “An exception of type ‘OpenQA.Selenium.DriverServiceNotFoundException’ occurred in WebDriver.dll but was not handled in user code ”

    I also tried with below code
    IWebDriver driver = new ChromeDriver(“C:\\Folder_with_Chrome_driver”);

    Still issue is there.

    How to resolve this issue?

    1. Hi Ankit,

      Have you added reference through manage nuget package for ‘selenium web driver’ and ‘chrome driver’?

  20. Hi Karthik,

    I liked your videos. They are very helpful. I have automated an application with Nunit. Now the thing is that I need to execute this code on the machines not having visual studio installed on it. Can you please suggest something in this.

  21. Hi. I have a few questions:
    Do you think its better to create a new project as a Class Library or Console Application and why?
    Do you use the same structure Set up, Test and Tear Down during each test?
    Do you use one class at the end of each test?
    Do you use page object mode to keep the code clean?

  22. Hi Karthik,
    am working with Selenium C#, while launching the browser am getting the error as “Unable to find the element in the closed window”.
    i have already tried bleow options and its vain.

    1.Try going to Internet Options –> Security –> “Enable Protected Mode” on ALL zones should either be checked or ALL unchecked.
    2.For 64-bit Windows: The key is HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BFCACHE

  23. Hello Karthik,

    I am using Nunit 3. And I am unable to use OneTimeSetup. I dont know the reason but OneTimeSetUp is not being invoked. I tried in different machines and its the same everywhere
    using NUnit.Framework;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    namespace Nunit3Sample
    {
    class testcase
    {
    [OneTimeSetUp]
    public void Onetimesetup()
    {
    Console.WriteLine(“OneTimesetup”);
    }
    [OneTimeTearDown]
    public void OneTimeTearDown()
    {
    Console.WriteLine(“OneTimeTearDown”);
    }
    [Test]
    public void testcase1()
    {
    Console.WriteLine(“testcase1”);
    }
    [SetUp]
    public void setup()
    {
    Console.WriteLine(“setup”);
    }
    [TearDown]
    public void teardown()
    {
    Console.WriteLine(“teardown”);
    }
    }
    }
    Kindly reply at the earliest possible

  24. Hi karthik,

    how can i run two tests in one class without opening new window for a web page
    for ex: i have written two methods in a class but for the second method it is opening new window for same web page and it is implementing that 2nd method there.

    Thanks,
    chari

  25. Hi Karthik,
    can selenium be used to create a web crawler to in xamarin as well. i have been getting error

    “OpenQA.Selenium.DriverServiceNotFoundException: The geckodriver file does not exist in the current directory or in a directory on the PATH environment variable.”

    whereas the same code runs well in other visual studio apps.
    i am using windows 10 64 bit machine and latest versions of selenium support and web drivers along with firefox driver.
    Many thanks in advance

    dev

  26. Hello Sir,

    Your videos are so helpful. Really interested for me. Thanks for such clear explanation. But I am facing 1 error. By running test it just show Black Console screen with a message “Press any key to continue”
    I read your all comments. But I am unable to find issue what’s wrong with my code. Please have a look into my code. Thanks in advance for your time.

    using NUnit.Framework;
    using OpenQA.Selenium;
    using OpenQA.Selenium.Chrome;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    namespace Nunit
    {
    class Program
    {
    //Create Global reference for our browser via WebDriver
    IWebDriver driver = new ChromeDriver();

    static void Main(string[] args)
    {
    }

    [SetUp]
    public void Initialize()
    {
    //Navigate to Execute automation demo page
    driver.Navigate().GoToUrl(“https://www.google.com.pk/”);
    Console.WriteLine(“Opened URL”);
    }
    [Test]
    public void ExecuteTest()
    {
    //Find the Element
    IWebElement element = driver.FindElement(By.Id(“q”));

    //Perform Ops
    element.SendKeys(“executeautomation”);

    Console.WriteLine(“Executed Test”);
    }

    [Test]
    public void NextTest()
    {
    Console.WriteLine(“Next method”);
    }

    [TearDown]
    public void CleanUp()
    {
    driver.Close();
    Console.WriteLine(“Closed the browser”);
    }

    }
    }

  27. Hi Kartik,
    I want to automate an android application(not a web app) using Nunit, Appium, Selenium, C#.
    I am trying to dial a number through my phone by accessing package and activity.
    below is my code.
    Not getting expected output.
    using NUnit.Framework;
    using OpenQA.Selenium.Appium.Android;
    using OpenQA.Selenium.Remote;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    namespace Tests
    {
    public class Tests
    {
    AndroidDriver driver;
    DesiredCapabilities cap;
    [SetUp]
    public void Setup()
    {

    cap = new DesiredCapabilities();
    cap.SetCapability(“platformName”, “Android”);
    cap.SetCapability(“platformVersion”, “5.0.1”);
    cap.SetCapability(“deviceName”, “lge-nexus_4-022f80d8490d8dfe”);
    cap.SetCapability(“appPackage”, “com.devicemanagement”);
    cap.SetCapability(“appActivity”, “MainActivity”);
    driver = new AndroidDriver(new Uri(“http://192.168.221.41:5002/wd/hub”), cap);
    }

    [Test]
    public void Test1()
    {

    Assert.IsNotNull(driver);
    System.Threading.Thread.Sleep(2000);
    }

    //Dail the number
    [Test]
    public void Test2()
    {
    //driver.FindElementByXPath(“//android.view.View[@content-desc=’Password’]/following-sibling::android.view.View/android.widget.EditText”).sendKeys(“Lakshay”);
    try
    {
    driver.FindElementByXPath(“//android.widget.ImageButton[@content-desc=’dial pad’]”).Click();
    driver.FindElementByXPath(“//android.widget.EditText”).Click();

    driver.FindElementByXPath(“//android.widget.TextView[contains(@resource-id,’dialpad_key_number’) and @text=’5′]”).Click();
    //driver.FindElementByXPath(“//android.widget.TextView[@text=’1′]”).Click();

    driver.FindElementById(“//android.widget.ImageButton[@content-desc=’dial’]”).Click();
    System.Threading.Thread.Sleep(2000);
    }
    catch(Exception e)
    {
    e.GetBaseException();
    }
    }

    [TearDown]
    public void closeDriver()
    {
    driver.Quit();
    }

    public static void main()
    {
    Tests t = new Tests();
    t.Setup();
    t.Test1();
    t.Test2();
    t.closeDriver();
    }
    }
    }

Leave a Reply

Your email address will not be published. Required fields are marked *