Using NUnit with Selenium C#

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

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

48 comments

  1. Colby says:

    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.

    • karthik KK says:

      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. Din says:

    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?

  3. Shalini says:

    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?

    • Karthik kk says:

      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

      • Shalini says:

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

        }
        }

        • Shalini says:

          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.

  4. Arch says:

    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. Ananth says:

    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 ?

  6. Lakshmi says:

    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. plbandara says:

    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. saurabh gupta says:

    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. saurabh gupta says:

    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. shilpa parashar says:

    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. Suma Patil says:

    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

    • Karthik kk says:

      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. sundaram says:

    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.

  13. PJ Champion says:

    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!

  14. Divya says:

    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 !!

  15. George says:

    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

  16. Natasha says:

    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.

    • Karthik kk says:

      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

      • Natasha says:

        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?

      • Natasha says:

        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.

      • Prashanthi says:

        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.

  17. Pav says:

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

    It opens up Google, but sendkeys are not working.

    • Pav says:

      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

        • Pav says:

          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

  18. Ankit says:

    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?

  19. Kishor says:

    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.

Leave a Reply

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