Selenium Webdriver & BDD With Specflow
Selenium Webdriver & BDD With Specflow
WITH
SPECFLOW 1
AND
SELENIUM WEBDRIVER
• INTERNSHIP 2020
AGENDA
1. SELENIUM WEBDRIVER
INTRODUCTION 2
WHY SELENIUM WEBDRIVER
ARCHITECTURE
SELENIUM GRID
LOCATING ELEMENTS WITH WEBDRIVER
WEBDRIVER WAIT
TEST DESIGN PATTERNS
PAGE OBJECT PATTERN
2
AGENDA
2. BDD & SPECFLOW
INTRODUCTION 3
BDD PRACTICES- SBE & TDD
TOOLS
FEATURE ELEMENTS
MULTIPLE SCENARIO STEPS
SCENARIO OUTLINES
TAGS
BACKGROUND ELEMENTS
3
AGENDA
LET’S AUTOMATE!
Q&A 4
RESOURCES
4
SELENIUM WEBDRIVER
5
INTRODUCTION
6
WHY SELENIUM WEBDRIVER
7
ARCHITECTURE
8
ARCHITECTURE
9
ARCHITECTURE
BROWSER DRIVERS
Selenium uses drivers, specific to each browser in order to establish a secure connection with the
browser without revealing the internal logic of browser's functionality. The browser driver is also
specific to the language used for automation such as Java, C#, etc. When we execute a test script
using WebDriver, the following operations are performed internally.
HTTP request is generated and sent to the browser10driver for each Selenium command.
The driver receives the HTTP request through HTTP server.
HTTP Server decides all the steps to perform instructions which are executed on browser.
Execution status is sent back to HTTP Server which is subsequently sent back to automation
script.
BROWSERS
Supported browsers: Firefox, Chrome, Internet Explorer, Edge, Safari, Opera, HtmlUnit (headless),
phantomjs.
10
SELENIUM GRID
• A server that allows tests to use web browser instances running on
remote machines
• One server acts as the hub => Tests contact the hub to obtain access
to browser instances. The hub has a list of servers that provide
access to browser instances (WebDriver nodes), and lets tests use
these instances. 11
• Selenium Grid allows running tests in parallel on multiple machines,
and to manage different browser versions and browser configurations
centrally (instead of in each individual test).
• The ability to run tests on remote browser instances is useful to
spread the load of testing across several machines, and to run tests
in browsers running on different platforms or operating systems. The
latter is particularly useful in cases where not all browsers to be used
for testing can run on the same platform.
11
HOW TO USE IT
- .NET – create a new project in Visual Studio and install the appropriate Selenium
Webdriver NuGet packages
- Java – create a new java project using Maven or Gradle and include Selenium
Webdriver as a dependency.
- Python – install the Selenium WebDriver module via pip (pip install selenium)
12 if you want to use the remote WebDriver.
- Download the standalone Selenium server
- Highly recommended is to use Selenium WebDriver from a unit testing
framework for the appropriate language (e.g. MsTest/Nunit for .NET,
Junit/TestNG for Java, Unittest/Pytest for Python)
- Create a new unit test project in whatever language and framework you are using,
then add Selenium WebDriver dependencies to the project.
- Google is your friend for the specifics
12
A SIMPLE EXAMPLE IN C#
//create an instance of a Firefox driver
IWebDriver driver = new FirefoxDriver();
//navigate to a url
driver.Navigate().GoToUrl("https://amazon.com/");
13
//enter text in the search box
driver.FindElement(By.Id(“twotabsearchtextbox”)).SendKeys(“Harry Potter”);
13
LOCATING ELEMENTS WITH WEBDRIVER
• By ID
• IWebElement element = driverOne.FindElement(By.Id("myUniqueId"));
• By CSS Selector
• IWebElement css = driverOne.FindElement(By.CssSelector("#green span.dairy.baged"));
• By Class
• IList<IWebElement> elements = driverOne.FindElements(By.ClassName("green“)
• By Tag Name
14
• IWebElement frame = driverOne.FindElement(By.TagName("iframe"));
• By Name
• IWebElement cheese = driverOne.FindElement(By.Name("goran"));
• By Link Text
• IWebElement link = driverOne.FindElement(By.LinkText("best features"));
• By Partial Link Text
• IWebElement link = driverOne.FindElement(By.PartialLinkText("features"));
• By Xpath
• IList<IWebElement> inputs = driverOne.FindElements(By.XPath("//input"));
14
IWEBELEMENT METHODS
Clear Clears the content of this element.
Click Clicks this element.
FindElement Finds the first IWebElement using the given method.
(Inherited from ISearchContext.)
FindElements Finds all IWebElements within the current context using the given
mechanism. 15
(Inherited from ISearchContext.)
GetAttribute Gets the value of the specified attribute for this element.
GetCssValue Gets the value of a CSS property of this element.
SendKeys Simulates typing text into the element.
Submit Submits this element to the web server.
15
IWEBELEMENT PROPERTIES
Displayed Gets a value indicating whether or not this element is displayed.
Size Gets a Size object containing the height and width of this element.
16
HTML ELEMENT ACTIONS IN WEBDRIVER
• Type text into a field => Use SendKeys() (good practice is to Clear() the field beforehand)
• IWebElement element = driver.FindElement(By.Name(“test"));
• element.Clear();
• element.SendKeys(“Entering some text");
• Click an element => Use Click() (in some cases you might have issues with that, a workaround is
using SendKeys(Keys.Enter)) 17
• element.Click();
• OR
• element.SendKeys(Keys.Enter);
• Select an item from a dropdown => Add a dependency to Selenium.Support in your project first
• SelectElement selectElement = new
SelectElement(driver.FindElement(By.XPath("/html/body/select")));
• selectElement.SelectByText(“Example"); //you can also select by value or id
17
ADVANCED INTERACTIONS
The Advanced User Interactions API is a new, more comprehensive API
for describing actions a user can perform on a web page. This includes
actions such as drag and drop or clicking multiple elements while
holding down the Control key.
dragAndDrop.Perform();
18
WEBDRIVER WAIT
19
EXPLICIT WAIT
• The explicit wait is used to tell the Web Driver to wait for certain conditions (Expected Conditions) or
the maximum time exceeded before throwing an "ElementNotVisibleException" exception.
• There are some convenience methods provided that help you write code that will wait only
as long as required. WebDriverWait in combination with ExpectedCondition is one way this
can be accomplished.
using (IWebDriver driver = new FirefoxDriver())
{ 20
driver.Url = "http://somedomain/url_that_delays_loading";
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
IWebElement myDynamicElement = wait.Until<IWebElement>(d => d.FindElement(By.Id("someDynamicElement")));
}
Expected Conditions
There are some common conditions that are frequently encountered when automating web browsers.
Example, Element is Clickable - it is Displayed and Enabled:
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
IWebElement element = wait.Until(ExpectedConditions.ElementToBeClickable(By.Id("someid")));
20
IMPLICIT WAIT
• An implicit wait is to tell WebDriver to poll the DOM for a certain amount of time when trying
to find an element or elements if they are not immediately available.
• The default setting is 0.
• Once set, the implicit wait is set for the life of the WebDriver object instance.
21
using (IWebDriver driver = new FirefoxDriver())
{
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);
driver.Url = "http://somedomain/url_that_delays_loading";
IWebElement myDynamicElement = driver.FindElement(By.Id("someDynamicElement"));
}
21
TEST DESIGN PATTERNS
• AAA Pattern – Arrange Act Assert
• Arrange – Setup code in preparation for launching the actual test actions (e.g. start a
WebDriver instance, navigate to a home page, etc.)
• Act – Perform an action or actions in order to reach the desired state of the application that
we want to test (e.g. perform a search for a certain item).
• Assert – make an assert to verify that the item under test behaves correct; a good practice is
to have one assert statement per test, because we want to have a single test covering a
22
single test case (e.g. Assert that the search result returned from the Act part of the test
matches the search query)
• Why we want to use this:
• It assures that tests have been kept simple and to the point and each have a
concrete responsibility
• Makes tests more maintainable AND more focused because when your test code
starts to deviate from being simple (e.g. it has multiple interleaved actions and
asserts), it tends to break this template in a way that is very obvious.
22
PAGE OBJECT PATTERN
• One of the most popular patterns in Web Automation is the so called Page Object
Pattern.
• To understand the primary goal of the pattern, first you need to think what your web
automation tests are doing. They navigate to different web pages and click/type
on/in various elements.
• The Page Object Pattern wraps all elements, actions and validations happening on
a page(or a part of the page, e.g. a login23form) in one single object- Page Object.
• The page objects are kept separately from the test code.
• The main pros of the Page Object Pattern are the readability and that it follows
the DRY (Do not Repeat Yourself) and Single Responsibility SOLID Principles.
• It helps you build easy to maintain tests that do not use element locators directly.
(make the elements private and expose action methods that can be used from the
test classes)
23
PAGE OBJECT PATTERN
24
24
PAGE OBJECT PATTERN
The Page Object pattern allows you to model a web page, exposing its “services” as public
methods.
• Create the page by defining a class that will model the specific page
• Describe the page by specifying the HTML elements you’ll use to interact with it.
• Use the page. by initializing the class as an object and calling its methods.
Before getting started with using the Page Object on a web page, ask yourself: “What am I
25 elements will I need to get those things
trying to do on this page?“, and then: What HTML
done?
Name the element -> Provide instructions on how to locate it. (Do name your page
elements descriptively, eg. UsernameTextbox, SubmitButton, etc.)
Create methods that define possible actions that can be performed on the page. (e.g.
Login action that contains entering text in username and password fields and clicking a login
button). Methods that don’t navigate away from the page should ideally return the same page
object, methods that navigate away should return a new page object.
In your tests you will instantiate a new Page object and will use its defined methods without
using the page elements directly.
25
BDD & SPECFLOW
26
26
BDD
27
• BDD lets software development teams describe how software should behave in
plain text.
27
BDD PRACTICES
The two main practices of BDD are Specification by Example (SbE) and Test
Driven Development (TDD)
28
INTRODUCTION
Advantages of TDD
• The developer needs to understand first, what the desired result should be and how to test it
before creating the code.
• The code for a component is finished only when the test passes and the code is refactored.
29is always up to the data.
• The Unit tests act as living documentation that
• If a defect is found, the developer creates a test to reveal that defect and then modify the
code so that the test passes and the defect is fixed. This reduces the debugging time. All the
other tests are also run and when they pass, it ensures that the existing functionality is not
broken
• The developer can make design decisions and refactor at any time and the running of the
tests ensures that the system is still working. This makes the software maintainable.
• On each successive test run, all the previous defect fixes are also verified and the repetition
of same defect is reduced.
• As most of the testing is done during the development itself, the testing before delivery is
shortened.
29
INTRODUCTION
Disadvantages of TDD
The starting point is User Stories, describing the behavior of the system. Hence, the developers
often face the following questions:
• When to test?
• What to test?
• How to know if a specification is met?
30
• Does the code deliver business value?
TDD vs BDD
TDD
• Describes how the software works.
BDD
• Describes how the end user uses the software.
• Fosters collaboration and communication.
• Emphasizes on examples of behavior of the System.
• Aims at the executable specifications derived from the examples
30
TOOLS. SPECFLOW
The development teams often have a misconception that BDD is a tool framework. In reality,
BDD is a development approach rather than a tool framework. However, as in the case of other
development approaches, there are tools for BDD also.
Several BDD Tools are in use for different platforms and programming languages- Cucumber
(Ruby framework), SpecFlow (.NET framework), 31Behave (Python framework), JBehave (Java
framework), JBehave Web (Java framework with Selenium integration), Jasmine (JavaScript
framework),Cucumber-js (JavaScript framework), etc.
31
FEATURE ELEMENTS
SpecFlow is an open-source project with source code, hosted on GitHub. The feature files used
by SpecFlow to store an acceptance criterion for features (use cases, user stories) in your
application are defined using the Gherkin syntax.
The Gherkin format was introduced by Cucumber and is also used by other tools.
Scenario outlines can be used to define data-driven acceptance tests. The scenario outline
always consists of a scenario template specification (a scenario with data placeholders using
the <placeholder> syntax) and a set of examples that provide values for the placeholders
• If the unit test framework supports it, SpecFlow
34 generates row-based tests from
scenario outlines.
• Otherwise, it generates a parameterized unit-test logic method for a scenario outline
and an individual unit test method for each example set.
• For better traceability, the generated unit-test method names are derived from the
scenario outline title and the first value of the examples (first column of the examples
table).
• It is therefore good practice to choose a unique and descriptive parameter as the first
column in the example set.
34
TAGS
Tags are markers that can be assigned to features and scenarios. Assigning a tag to
a feature is equivalent to assigning the tag to all scenarios in the feature file. A Tag
Name with a leading @ denotes tag.
35 SpecFlow generates categories from
• If supported by the unit test framework,
the tags.
• The generated category name is the same as the tag's name, but without the
leading @.
• You can filter and group the tests to be executed using these unit test
categories. For example, you can tag crucial tests with @important, and then
execute these tests more frequently.
35
BACKGROUND ELEMENTS
The background language element allows specifying a common precondition for all scenarios in
a feature file
• The background part of the file can contain one or more scenario steps that are
executed before any other steps of the scenarios.
36
• SpecFlow generates a method from the background elements that is invoked from all
unit tests generated for the scenarios.
36
LET’S AUTOMATE!
Setting Up your SpecFlow Project
The easiest and most convenient way to set up such projects is to use SpecFlow NuGet
package or one of the specific helper packages, like SpecRun.SpecFlow or SpecFlow.NUnit.
Create a new Unit Test Project / MSTest Test Project
37
LET’S AUTOMATE!
Executing Your First Test
SpecFlow+ Runner integrates with Visual Studio Test Explorer. After adding your first
specification and building the solution, the business readable scenario titles will show up in
Visual Studio Test Explorer:
Build your solution.
Select Test | Windows | Test Explorer to open the Test Explorer
38
Scenarios are displayed with their plain text scenario title (not the generated test name).
Click on Run All to run your test. As the automation and application code has not yet been
implemented, the test will not pass successfully.
Note: The evaluation version of SpecFlow+ Runner delays the execution of your tests by a
number of seconds each time. You can request a free license key to remove this restriction
(please include your name and company name).
38
PIECE OF CODE
39
39
PIECE OF CODE
40
40
41
41
42
42
Q&A
• Questions?
43
43
RESOURCES
• Selenium WebDriver official docs
• https://www.seleniumhq.org/docs/index.jsp
• https://github.com/SeleniumHQ/selenium/wiki
• Selenium WebDriver with C# - Advanced design patterns. BG authors.
• https://www.automatetheplanet.com/
• https://alexanderontesting.com/2019/10/28/c-pagefactory-wrap-your-webdriver-calls/
44 through more advanced concepts
• Selenium WebDriver with Java – covers beginner
• http://artoftesting.com/selenium-tutorial.html
• BDD & SpecFlow
• https://www.tutorialspoint.com/behavior_driven_development/behavior_driven_devel
opment_and_specflow.htm
• BDD Framework: A Complete Tutorial
• https://www.softwaretestinghelp.com/bdd-framework/
• Google and StackOverflow are your friends, do learn to use them
44
THANK YOU!
45
IVAYLO DINKOV
TEST CONSULTANT
YOAN ZHELYAZKOV
TEST ENGINEER