Automation in .NET

To write this tutorial, I split the work environment in two solutions:

  1. Project: WebSite (Website to test)
  2. Project: Automation (Test Automation host)


1. WebSite Project

First of all, we will start creating our solution for test through the following steps:

First open visual studio, then new project and then select a new project of type MVC5 template integrated in the visual studio (WebSite).


2. Automation Project

Now, we can proceed to create other solution for the Automation Test of Class Library type:

Automation (1)

Then install all libraries necessary to compile and run our automation project through the panel admin Nuget Packages, here the list of libraries that do you need install:

  • Selenium.Support
  • Selenium.WebDriver
  • NUnit
  • NUnitTDNet
  • FluentAssertions
  • TestDriven.Net (Optional)

Now is necessary create our structure to write the code, splitting the methods and test in each respective class:

  • TestBase.cs
  • GlobalsWords.cs
  • Elements.cs
  • AHomePageTest.cs
  • BRegisterPageTest.cs
  • CLogInPageTest.cs


2.1 Class TestBase.cs

Before to show the code of this class is important know and understand the life cycle of the test execution, in the next picture you can view the logic model in priority order.


This is used at the moment when you have a lot of test and you want to continue executing another test without their browser process ends or is closed.

 protected IWebDriver driver;

Declare the instance the WebDriver.

 public void OneTimeSetUp()
 driver = new FirefoxDriver();

protected virtual void OnOneTimeSetUp(){}

Declare the method OneTimeSetUp with the attribute “[OneTimeSetUp]” included in the NUnit.Framework, this method create a new instance the Webdriver using the browser integrated by default Firefox, once upon the browser opened the window will expand to full screen. Later we define the method “OnOneTimeSetUp” empty to overwrite in the test pages.

 public void SetUp()
 Console.WriteLine(@"Running {0}", GetTestName());

private static string GetTestName()
 return TestContext.CurrentContext.Test.FullName;

protected virtual void OnSetUp(){}

The method Setup use the attribute “[SetUp]“, this method write in the console the full name including namespace of the automation test in current execution.

 public void TearDown()
 string ResultTest = string.Empty;
 ResultTest = TestContext.CurrentContext.Result.Outcome.Status.ToString();
 if (driver == null) return;

 try {//Here the code to capture javascipt errors }
 if (ResultTest.Equals("Failed"))
 CaptureImage(ResultTest, string.Empty);
 Console.WriteLine(@"" + ResultTest + " {0}", GetTestName());

private void CaptureImage(string folder, string captureName)
 var captureDriver = driver as ITakesScreenshot;
 if (captureDriver != null)
 var screenshot = captureDriver.GetScreenshot();
 var path = Path.Combine(TestContext.CurrentContext.WorkDirectory, folder);
 if (!Directory.Exists(path))

 string captureSuffix = string.Empty;
 if (!string.IsNullOrEmpty(captureName))
 captureSuffix = "_" + captureName;

 var filename = string.Format("{0}{1}.png", TestContext.CurrentContext.Test.FullName, captureSuffix);
 screenshot.SaveAsFile(Path.Combine(path, filename), ImageFormat.Png);

The method TearDown use the attribute “[TearDown]“, this method write in the console the status the test execution and later use one try – finally block to capture errors of javascript type and save a screenshot in case of failed status.

 public void OneTimeTearDown()
 if(driver != null)

The method OneTimeTearDown use the attribute “[TearDown]“, this method verify if the driver is not null, in this case close, destroy and delete the process associated to driver, Here more details about the methods:

  • WebDriver.Quit() This method is used to destroy the instance of WebDriver. It closes all Browser Windows associated with that driver and safely ends the session. WebDriver.Quit() calls Dispose.


2.2 Class GlobalWords.cs

Before of that you create your test you should make an inspection of all response messages of your website or the words in the section that you want make a test, this is a good practice.

 public static string URLPage = "http://localhost:51492/";
 public static string EmailTest = string.Empty;
 public static string PasswordTest = "Kevin#"+DateTime.UtcNow.Year.ToString();

#region HomePage

 public static string TitlePageHome = "Home Page - My ASP.NET Application";

 public static string HomeTitle = "ASP.NET";
 public static string HomeParagraph = "ASP.NET is a free web framework for building great Web sites and Web applications using HTML, CSS and JavaScript.";
 public static string Homelink = "";

 public static string HomeSubtitleCol1 = "Getting started";
 public static string HomeParagraphCol1 = "ASP.NET MVC gives you a powerful, patterns-based way to build dynamic websites that enables a clean separation of concerns and gives you full control over markup for enjoyable, agile development.";
 public static string HomeSublinkCol1 = "";

 public static string HomeSubtitleCol3 = "Web Hosting";
 public static string HomeParagraphCol3 = "You can easily find a web hosting company that offers the right mix of features and price for your applications.";
 public static string HomeSublinkCol3 = "";

 public static string HomelinkText = "Learn more »";

#endregion HomePage
  • URLPage: variable used to reference the main page link
  • EmailTest: variable used to save the email created in the test
  • PassWordTest: variable used to save the password created in the test

2.3 Class Elements.cs

Sometimes you need to modify the timeout of a method or any additional feature that not is supported in the Selenium library, here an example about how can overload the method “FindElement” and setting the TimeOut as a parameter.

public static IWebElement FindElement(this IWebDriver driver, By by, int timeoutInSeconds)
 IWebElement element = null;
 if (timeoutInSeconds > 0)
 var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(timeoutInSeconds));
 element = wait.Until(ExpectedConditions.ElementExists(by));
 element = null;

 Assert.IsNotNull(element, "Can't find the element: " + @by);
 return element;

At the moment to capture the tag components a tool very useful can be Firepath and Firebug (Firefox plugins) here you can install, and a little explanation about how to use to reference in the tag with CSS selector through the next images.

public static void ButtonClick(this IWebDriver driver)
 var ButtonRegister = driver.FindElement(By.CssSelector(".btn.btn-default"));

public static void SendTextToField(this IWebDriver driver, string IdField, string text)
 var EmailField = driver.FindElement(By.Id(IdField));

2.4 Class AHomePageTest.cs

The class use the attribute “[TestFixture]” of NUnit.Framework, this class derive from TestBase to use all methods.

 public class AHomePageTest : TestBase {}

We can override the “OnSetup” method to indicate the URL to open at the start and validate the title page.

 protected override void OnSetUp()
 Assert.AreEqual(GlobalsWords.TitlePageHome, driver.Title, msgerror(GlobalsWords.TitlePageHome, driver.Title));

The best way to write your test is defining a good name, for example, TestCase###_LittleDescriptionHere.

 public void TestCase001_ValidateSectionUpHome()
 var Title = driver.FindElement(By.ClassName("jumbotron")).FindElement(By.TagName("h1"));
 Assert.AreEqual(GlobalsWords.HomeTitle, Title.Text, msgerror(GlobalsWords.HomeTitle, Title.Text));

 var paragraph = driver.FindElement(By.ClassName("lead"));
 Assert.AreEqual(GlobalsWords.HomeParagraph, paragraph.Text, msgerror(GlobalsWords.HomeParagraph, paragraph.Text));

 var link = driver.FindElement(By.CssSelector(".btn.btn-primary.btn-lg"));
 Assert.AreEqual(GlobalsWords.HomelinkText, link.Text, msgerror(GlobalsWords.HomelinkText, link.Text));

 Assert.AreEqual(GlobalsWords.Homelink, driver.Url, msgerror(GlobalsWords.Homelink, driver.Url));

To continue you can see a little demo about how you can run this example:

Demo Automation

here you can download the complete code of the example.

Thanks, I hope it is of your liking this article.


3 thoughts on “Automation in .NET

  1. I am now trying Ubuntu on Windows and I’ve been checking tutorials from different websites and blogs to see how it works. There is this guy Scott Hanselman, who have a great website about different things.

    I’ve seen that in his tutorial posts he have videos, or if it is simple enough the posts are like this one. I would encourage you to create a YouTube channel. Specially with tutorials in spanish, since usually they are pretty lousy in spanish in this kind of topics.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.