User Interface Unit Tests with .NET Core
In a previous post I talked about doing unit tests with .NET Core. What I didn’t cover was unit testing for the user interface (UI). It is actually something quite common, and we will see how we can do it now.
Selenium is a portable software-testing framework for web applications and there is a .NET port of it. We will be using the Selenium.WebDriver package, plus one or more of the following, to target different browsers:
- Selenium.Chrome.WebDriver: for Chrome
- Selenium.Firefox.WebDriver: for Firefox
- Selenium.WebDriver.MicrosoftWebDriver: for IE and Edge
Selenium offers a “minimum” contract that works across all browsers.
I won’t go through all of it, but I will give you some examples on how it works. We start by instantiating a driver:
using (var driver = (IWebDriver) new ChromeDriver(Environment.CurrentDirectory))
{
//...
}
driver
.Navigate()
.GoToUrl("http://www.google.com");
var elm = driver.FindElement(By.Name("q"));
- Id: By.Id
- CSS class: By.ClassName
- CSS selector: By.CssSelector
- Tag name: By.TagName
- Link text: By.LinkText
- Partial link text: By.PartialLinkText
- XPath: By.XPath
Once we find an element, we can access its properties:
var attr = elm.GetAttribute("class");
var css = elm.GetCssValue("display");
var prop = elm.GetProperty("enabled");
Then we can send it text strokes:
elm.SendKeys("asp.net core");
Or click on it:
elm.Click();
var timeouts = driver.Manage().Timeouts();
timeouts.ImplicitWait = TimeSpan.FromSeconds(1);
timeouts.PageLoad = TimeSpan.FromSeconds(5);
var waitForElement = new WebDriverWait(driver, TimeSpan.FromSeconds(5));
var logo = waitForElement.Until(ExpectedConditions.ElementIsVisible(By.Id("hplogo")));
- AlertIsPresent
- AlertState
- ElementExists
- ElementIsVisible
- ElementSelectionStateToBe
- ElementToBeClickable
- ElementToBeSelected
- FrameToBeAvailableAndSwitchToIt
- InvisibilityOfElementLocated
- InvisibilityOfElementWithText
- PresenceOfAllElementsLocatedBy
- StalenessOf
- TextToBePresentInElement
- TextToBePresentInElementLocated
- TextToBePresentInElementValue
- TitleContains
- TitleIs
- UrlContains
- UrlMatches
- UrlToBe
- VisibilityOfAllElementsLocatedBy