Cucumber test example

Cucumber test example DEFAULT

Post summary: Code examples and introduction to Cucumber, a framework that runs automated tests written in behavior driven development (BDD) style.

Cucumber examples can be found in selenium-samples-java/cucumber-parallel GitHub repository.

Before going into details how to create tests with Cucumber first is good to do some context introduction why this framework is created and getting more popular.

Test-driven development (TDD)

TDD (test driven development) is software development process in which developers first write the unit tests for feature or module based on requirements and then implement the feature or module itself. In short TDD cycle is “red > green > refactor”:

  • Red – phase where tests are implemented according to requirements, but they still fail
  • Green – phase where module or feature is implemented and tests pass
  • Refactor – phase where a working code is made more readable and well structured

Behaviour-driven development (BDD)

BDD emerged from and extends TDD. Instead of writing unit tests from specification why not make the specification a test itself. The main idea is that business analysts, project managers, users or anyone without technical, but with sufficient business, knowledge can define tests.

Gherkin

BDD ideas sound very nice but actually are not so easy to put in practice. In order to make documentation sufficient for testing, it should follow some rules. This is where Gherkin comes in place. It is a Business Readable, Domain Specific Language created especially to describe behavior without defining how to implement it. Gherkin serves two purposes: it is your project’s documentation and automated tests.

Cucumber

Cucumber is not a testing tool it is a BDD tool for collaboration between all members of the team. So if you are using Cucumber just for automated testing you can do better. Testwise Cucumber is a framework that understands Gherkin and runs the automated tests. It sounds like a fairy tale, you get your documentation described in Gherkin and tests just run. Actually, it is not that simple, each step from documentation should have underlying test code that manipulates the application and should have test conditions. All process will be described in details with code samples below.

Setup Maven project

The proper way to do things is by using some build automation tool. Most used ones are Gradle and Maven. Maven is more simple to use and works fine for normal workflows. Gradle can do anything you want to do, but it comes at a price of complexity since you have to write Groovy code for custom stuff. In order to use Cucumber-JVM (Cucumber implementation for the most popular JVM languages: Java, Groovy, Scala, etc.) in Java 8 POM looks like this:

In order to build project in Java 8 this should be specified explicitly in POM by using maven-compiler-plugin:

Once the project is setup then real Cucumber usage can start.

Feature files

Everything starts with a plain text file with .feature extension written in Gherkin language that describes only one product feature. It may contain from one to many scenarios. Below is a file with a simple scenario for searching in Wikipedia.

In Gherkin, each line that isn’t blank has to start with a Gherkin keyword, followed by any text you like. The main keywords are:

  • Feature
  • Scenario
  • Given, When, Then, And, But (Steps)
  • Background
  • Scenario Outline
  • Examples

More information can be found in Cucumber reference page.

Don’t repeat yourself

In some features, there might be one and the same Given steps before each scenario. In order to avoid copy/paste, it is better to define those steps as feature prerequisite with Background keyword.

Data-driven testing

Cucumber makes it very easy to handle cases of different business scenarios with different input data and different results based on that input data. The scenario is defined with Scenario Outline. Then data is fed to this scenario with Examples table where variables are defined with concrete values. The example below shows a scenario where a search is done for two keywords and expected results for each is defined. It is very easy just to add more keywords and expected result which is actually treated by Cucumber reporting as a different scenario.

Organise features and scenarios

Tags can be used in order to group feature files. A tag can be applied as annotation above Feature or Scenario keyword in .feature file. Having correctly tagged different scenarios or features runners can be created per each tag and run when needed. See more for tags in Cucumber tags page.

Runners

Next step in the process is to add runners. Cucumber supports running tests with JUnit and TestNG. In the current post, JUnit will be used. It has been imported in POM project file with cucumber-junit. In order to run a test with JUnit a special runner class should be created. The very basic form of the file is an empty class with @RunWith(Cucumber.class) annotation.

This will run the tests and JUnit results file will be generated. Although it works it is much better to provide some Cucumber options with @CucumberOptions annotation.

Runner above runs all feature files which does not have tag @ignored and outputs the results in three different formats: JSON in target/cucumber/wikipedia.json file, HTML in target/cucumber/wikipedia.html and Pretty – a console output with colours. All formatting options are available in Cucumber options page.

Runners strategy

Different runners can be created for different purposes. There could be runners based on specific tags and those to be invoked in specific cases like regression and smoke testing, or full or partial regression testing. Depends on the needs. It is possible to create runners for each feature and run tests in parallel. There is a way to automatically generate runners and run tests in parallel. This will speed up execution and will keep the project clean from unessential runners. More details can be found in Running Cucumber tests in parallel post.

Runners feature file

If the runner is not linked to any feature file (no features section defined in @CucumberOptions, like the one shown above) then runner automatically searches for all feature files in current and all child folders.

Java package structure is represented as a folder structure. Feature files can be placed in some package structure in resources folder of the project, e.g. com.automationrhapsody.cucumber.parallel.tests.wikipedia. When compiled those are copied to same folder structure in the output. So in order to run all feature files from package above runner class need to be placed in the same package in java folder of the project. It is possible to place the runner in parent package and it will still work as it searches all child folders e.g com.automationrhapsody.cucumber.parallel.tests will work. Placing in a different package will not work though, e.g. com.automationrhapsody.cucumber.parallel.tests.other will not work. There will be a message:

None of the features at [classpath:com/automationrhapsody/cucumber/parallel/tests/other] matched the filters: [[email protected]]

This means either there are no feature files into com.automationrhapsody.cucumber.parallel.tests.otherresources package or those files have tag @ignored.

The easiest way is to put just one runner into default package and it will run all feature files available. This gives more limitations than benefits in the long run though.

Running feature files without step definitions

So far feature file and the runner has been created. If now tests are started build will successes but tests will be skipped. This is because there is no implementation available for Given, When, Then commands in the feature file. Those should be implemented and Cucumber gives hints in build output how to do it.

Step definitions code / glue

So far feature file has been defined with a runner for it. In terms of BDD this is OK, but in terms of testing a step, definitions should be created so tests can actually be executed. As shown in hint above a method with annotation @Given is needed. Annotation text is actually a regular expression this is why it is good to start with ^ and end with $ which means the whole line from the feature file to be matched. In order to make the step reusable, some regular expression can be added in order to be able to pass different search terms, not only ‘Cucumber’. If there is regular expression defined then the method can take arguments which will be actually what regex will match in feature file text. Step definition for Given command is:

(.*?) is very basic regex, but it can do the work. It matches all zero or more characters surrounded by quotes in the end of the line after “Enter search term ” text. Once matched this is passed as argument to searchFor() method invocation.

Full step definitions for initial feature file are shown in class below:

Before and After

As noticeable above there is method annotated with @Before. This is executed before each scenario being run. It is used to allocate resources needed for a particular scenario to run. It is a good idea to instantiate WebDriver into this method. @After method is run at the end of the scenario so this is where resources are released, e.g. quitting WebDriver.

Page objects

Steps definitions code above is NOT well written. It is not a good idea to locate elements directly in the method where they are used. Never do this in real automation! Always use Page Object pattern. More details on it can be found in Page objects design pattern post.

Conclusion

BDD as an idea is good as it is according to Agile methodologies and stories definitions. Cucumber is very good BDD tool giving lots of flexibility and features with a big community supporting it. Cucumber-JVM is very easy to start working with. Be careful though, when steps definitions grow in count the main challenge will be to make those reusable. Challenge will be to avoid writing new steps code if such is already written for semantically the same commands but written in different words.

Related Posts

Sours: https://automationrhapsody.com/introduction-to-cucumber-and-bdd-with-examples/

Create an empty Cucumber project

In this quick tutorial you will learn how to:

  • Install Cucumber
  • Write your first Scenario using the Gherkin syntax
  • Write your first step definition in JavaJavaScriptKotlinRuby
  • Run Cucumber
  • Learn the basic workflow of Behaviour-Driven Development (BDD)

We’ll use Cucumber to develop a small library that can figure out whether it’s Friday yet.

Please be aware that this tutorial assumes that you have a:

  • Basic understanding of the Java programming language
  • Basic understanding of the Gradle file
  • Basic understanding of the Kotlin programming language
  • Basic understanding of the Gradle file
  • Basic understanding of the Javascript programming language
  • Basic understanding of the Ruby programming language
  • Basic understanding of the Bundler tool and
  • Some experience using a terminal
  • Some experience using a text editor

Before we begin, you will need the following:

Open a terminal to verify that Node.js is installed properly:

Both of these commands should print a version number.

Open a terminal to verify that Ruby is installed properly:

Both of these commands should print a version number.

Decide whether you’d prefer to use Gradle or Maven.

With Maven

For Maven, we’ll start by creating a new project directory with the Maven plugin. Open a terminal, go to the directory where you want to create your project, and run the following command:

You should get something like the following result:

Change into the directory that was just created by running the following command:

Open the project in IntelliJ IDEA:

  • File -> Open… -> (Select the pom.xml)
  • Select Open as Project

With Gradle

One way to create this sample Cucumber project using Gradle is to convert the above generated Maven archetype into a Gradle project.

Run the following command from the directory:

Add following dependency configuration to your build.gradle file:

Add the following Task to your file:

Note that you also need to add the necessary dependencies/configurations to depending on which version of Gradle you are using. See the Build Tools section. If you follow this guide be sure to set your path to for this tutorial.

If you have not already, open the project in IntelliJ IDEA:

  • File -> Open… -> (Select build.gradle)
  • Select Open as Project

Decide whether you’d prefer to use Gradle or Maven.

With Maven

For Maven, we’ll start by creating a new project directory with the Maven plugin. Open a terminal, go to the directory where you want to create your project, and run the following command:

You should get something like the following result:

Change into the directory that was just created by running the following command:

Open the project in IntelliJ IDEA:

  • File -> Open… -> (Select the pom.xml)
  • Select Open as Project

With Gradle

One way to create this sample Cucumber project using Gradle is to convert the above generated Maven archetype into a Gradle project.

Run the following command from the directory:

Add following dependency configuration to your build.gradle file:

Add the following Task to your file:

Note that you also need to add the necessary dependencies/configurations to depending on which version of Gradle you are using. See the Build Tools section. If you follow this guide be sure to set your path to for this tutorial.

If you have not already, open the project in IntelliJ IDEA:

  • File -> Open… -> (Select build.gradle)
  • Select Open as Project

To use Kotlin, we need to add it to our project:

  • Add a directory named in your directory and mark it as . In IntelliJ, you can do so by right-clicking on the directory and selecting “Mark Directory as” > “Test Sources Root”.
  • Create the package inside the directory.
  • Create a Kotlin class called inside the package. IntelliJ might tell you that Kotlin is not configured; click “Configure”. Your should now look like this:
  • Copy the annotations from the class to the class. If you are using IntelliJ, it will offer to translate the Java code to Kotlin code. Otherwise you’ll have to write your own.

Your class should now look like this:

  • Now you can delete the class.
  • Create a Kotlin class called inside the package.
  • Copy the import statements from to ; you’ll need them later.
  • Finally, delete the class (or even the directory).

To use Kotlin in our project, we need to take some extra steps:

  • Add a directory named in your directory and mark it as . In IntelliJ, you can do so by right-clicking on the directory and selecting “Mark Directory as” > “Test Sources Root”.
  • Create the package inside the directory.
  • Create a Kotlin class called inside the package and copy the annotations from the class to the class. If you are using IntelliJ, it will offer to translate the Java code to Kotlin code. Otherwise you’ll have to write your own.

Your class should now look like this:

We’ll start by creating a new directory and an empty Node.js project.

Add Cucumber as a development dependency:

Open in a text editor and change the section so it looks like this:

Prepare the file structure:

Create a file called at the root of your project and add the following content:

Also, create a file called with the following content:

We’ll start by creating a new directory and an empty Ruby project.

Create a with the following content:

Install Cucumber and prepare the file structure:

You now have a small project with Cucumber installed.

To make sure everything works together correctly, let’s run Cucumber.

Maven:

Gradle:

Maven:

Gradle:

You should see something like the following:

Cucumber’s output is telling us that it didn’t find anything to run.

When we do Behaviour-Driven Development with Cucumber we use concrete examples to specify what we want the software to do. Scenarios are written before production code. They start their life as an executable specification. As the production code emerges, scenarios take on a role as living documentation and automated tests.

Try running an Example Mapping workshop in your team to design examples together.

In Cucumber, an example is called a scenario. Scenarios are defined in files, which are stored in the directory (or a subdirectory).

One concrete example would be that Sunday isn’t Friday.

Create an empty file called with the following content:

The first line of this file starts with the keyword followed by a name. It’s a good idea to use a name similar to the file name.

The second line is a brief description of the feature. Cucumber does not execute this line because it’s documentation.

The fourth line, is a scenario, which is a concrete example illustrating how the software should behave.

The last three lines starting with , and are the steps of our scenario. This is what Cucumber will execute.

Now that we have a scenario, we can ask Cucumber to execute it.

Maven:

Gradle:

Maven:

Gradle:

Cucumber is telling us we have one scenario and three steps. It’s also suggesting some snippets of code that we can use to define these steps:

Copy each of the three snippets for the undefined steps and paste them into .

Unfortunately, Cucumber does not generate snippets in Kotlin. But fortunately IntelliJ can convert the Java code to Kotlin code for you. You might need to improve the translated code, to make it more idiomatic. You might also need to add the following import statements (if you hadn’t already).

Your file should now look like this:

Run Cucumber again. This time the output is a little different:

Cucumber found our step definitions and executed them. They are currently marked as pending, which means we need to make them do something useful.

The next step is to do what the comments in the step definitions is telling us to do:

Write code here that turns the phrase above into concrete actions

Try to use the same words in the code as in the steps.

If the words in your steps originated from conversations during an Example Mapping session, you’re building a Ubiquitous Language, which we believe is a great way to make your production code and tests more understandable and easier to maintain.

Change your step definition code to this:

Run Cucumber again:

That’s progress! The first two steps are passing, but the last one is failing.

Let’s do the minimum we need to make the scenario pass. In this case, that means making our methodfunctionblockfunctionfunction return :

Run Cucumber again:

Congratulations! You’ve got your first green Cucumber scenario.

The next thing to test for would be that we also get the correct result when it is Friday.

Update the file:

We’ll need to add a step definition to set to “Friday”:

When we run this test, it will fail.

That is because we haven’t implemented the logic yet! Let’s do that next.

We should update our statement to actually evaluate whether or not is equal to .

Run Cucumber again:

So, we all know that there are more days in the week than just Sunday and Friday. Let’s update our scenario to use variables and evaluate more possibilities. We’ll use variables and examples to evaluate Friday, Sunday, and anything else!

Update the file. Notice how we go from to when we start using multiple .

We need to replace the step definitions for and with one step definition that takes the value of as a String. Update the file as follows:

Run Cucumber again:

Now that we have working code, we should do some refactoring:

  • We should move the methodfunctionblockfunctionfunction out from the test code into production code.

  • We could at some point extract helper methods from our step definition, for methodsfunctionsfunctionsblocks we use in several places.

In this brief tutorial you’ve seen how to install Cucumber, how to follow the BDD process to develop a methodfunctionblockfunctionfunction, and how to use that methodfunctionblockfunctionfunction to evaluate multiple scenarios!

Sours: https://cucumber.io/docs/guides/10-minute-tutorial/
  1. Gatlinburg log cabin rental
  2. Hotels pyeongchang
  3. Allergy index orlando

What is Scenario in Cucumber Testing?

next →← prev

The scenario is one of the core structures of the Gherkin language. Scenario includes all the possible circumstances of the feature and test scripts for these circumstances.

The keyword "Scenario" represents a scenario in Gherkin language.

One feature can have multiple scenarios, and each scenario consists of one or more steps.

Scenario in Cucumber Testing

Let's understand the scenario through an example:

Example:

In order to ensure Feedback functionality of a web application, we are creating a cucumber test to verify whether it is working or not.

Scenario - Verification of Feedback Functionality Given the user navigates to JavaTpoint.comWhen the user clicks on Feedback, then the Feedback page opens And the user submits feedback message Then feedback should be received on the admin page And admin can reply to the user

Each scenario follows the Given, When, And, and Then format. This format comes under a particular language, called "Gherkin language".

  • Given: It describes the task of a particular function of an application. It is basically a pre-known state or pre-condition for testing.
  • When: It is used to describe the action. For example, when the user tries to login, it is considered as an action.
  • Then: The expected result should be placed here. For example, the verification of a successful login is a result.
  • And: We can use it to combine two or more actions of the same type. For example, username and password belong to the same type, i.e., login function.

Scenario Outline

In Gherkin language, scenario outline is the keyword which is used to run the same scenario multiple times.

It is also defined as "Scenario outlines are used when the same test is performed multiple times with a different combination of values."

The keyword scenario outline can also be used by the name Scenario Template. In other words, the keyword Scenario Template is a synonym of scenario outline.

Scenario outline is exactly similar to the scenario structure, but the only difference is the provision of multiple inputs. In order to use scenario outlines, we do not need any smart idea, we just need to copy the same steps and re-execute the code.

Let's understand the scenario outline through an example:

Example:

Suppose we need to test whether the login functionality for multiple users is working properly or not. This case requires the execution of the login functionality scenario multiple times. Hence, the scenario outline can be used for the testing of login functionality scenario with multiple usernames and passwords.

While mentioning variables such as "Username" and "Password" in gherkin statements, mention them with "<>". Consider the following test script:

Scenario: Successful Login with Valid entries Given user navigates to the website javatpoint.comWhen User Navigate to Login Page And user logs in through Login Window by using <Username> as "username1" And <Password> as "password1" Then login must be successful.

Let's take the above test script, in which we need to test login functionality with several different sets of username and password.

Feature: Login Functionality Scenario Outline: Login functionality Username | Password username1 | password1 username2 | password2 username3 | password3 username4 | password4

In the above example, we have provided multiple input values for the variables "Username" and "Password". While executing the actual test, Cucumber will replace the variables with the provided input values.

Once username1 has been executed with password1, the test will execute for the second iteration with another input value. Cucumber will follow this path until the completion of all provided values.

Note: A Scenario Outline must contain a Scenario section. Scenario steps are interpreted as a template and never executed directly.


Next TopicInstall Cucumber Eclipse Plugin



← prevnext →



Sours: https://www.javatpoint.com/scenario-in-cucumber-testing
Selenium Cucumber Java BDD Framework 4 - Sample Login Test

In this tutorial, you will learn how to integrate Cucumber with Selenium Webdriver.

What is Cucumber?

Cucumber is a testing approach which supports Behavior Driven Development (BDD). It explains the behavior of the application in a simple English text using Gherkin language.

Learn more at – https://www.guru99.com/cucumber-tutorials.html

What is Selenium?

Selenium is an automation tool for Functional Testing of the web-based application. Selenium supports different language like java, ruby, python C#, etc.

Learn more at – https://www.guru99.com/selenium-tutorial.html

In this Cucumber tutorial, we will learn-

Why use Cucumber with Selenium?

Cucumber and Selenium are two popular technologies.


Most of the organizations use Selenium for functional testing. These organizations which are using Selenium, want to integrate Selenium with Cucumber as Cucumber makes it easy to read and to understand the application flow.

Cucumber tool is based on the Behavior Driven Development framework that acts as the bridge between the following people:

  1. Software Engineer and Business Analyst.
  2. Manual Tester and Automation Tester.
  3. Manual Tester and Developers.

Cucumber BDD framework also benefits the client to understand the application code as it uses Gherkin language which is in Plain Text. Anyone in the organization can understand the behavior of the software. The syntax’s of Gherkin is in simple text which is readable and understandable.

Why use Cucumber with Selenium

Prerequisite for using Cucumber with Selenium

Before we start Cucumber Selenium integration, we need the following items:

  • Selenium jar files:
  • Selenium-server-standalone

Can be downloaded at http://www.seleniumhq.org/download/

Download Selenium Standalone Server

Jar files For Cucumber :

  • Cucumber-core
  • Cucumber-html
  • cobertura code coverage
  • Cucumber-java
  • Cucumber-junit
  • Cucumber-jvm-deps
  • Cucumber-reporting
  • Hamcrest-core
  • Gherkin
  • Junit

Can be downloaded at https://mvnrepository.com/search?q=Cucumber

You need to search files and download them one by one individually.


For example, we will show you to download one of the jar files, i.e., “Cucumber-core.”

Click on the above download link. It redirects to the below site. Now search the particular jar, i.e. ‘Cucumber Core’ as shown screenshot below:

Download Cucumber Core

In the next page, Click of the version 1.2.2,

Download Cucumber Core

In the next screen, click on download to get the ‘Cucumber Core’ jar file.

Download Cucumber Core

Note: For your ease, we have bundled the jar files required to be download from Maven here. With time these jars maybe updated and become incompatible. You are requested to download them using the method illustrated above.

Automation Testing Using Cucumber with Selenium.

Let’s study steps to use Cucumber with selenium step by step. Here we will cover 3 scenarios:

  • Scenario 1: Print text in the console.
  • Scenario 2: Enter login Credential and reset the value.
  • Scenario 3: Enter login Credential on Guru99 & reset the value. Do this for 3 sets of data.

Scenario 1: Print text in the console.

In this scenario, we just print the text in the console by using Cucumber.


Step 1)Create Project in eclipse.

Create Java project with the name “CucumberWithSelenium” as shown in the below screenshot.

Automation Testing Using Cucumber with Selenium

Automation Testing Using Cucumber with Selenium

Step 2) Adding Jar files in the project.

Right Click on the Project > Select Properties > Go to Java Build Path. Add all the libraries downloaded earlier.

Automation Testing Using Cucumber with Selenium

Step 3) Creating feature file

For creating feature file first create features folder as shown below screenshot.

Automation Testing Using Cucumber with Selenium

Now Enter Folder name ‘Features’ and click on ‘Finish’ Button.

Automation Testing Using Cucumber with Selenium

Automation Testing Using Cucumber with Selenium

Now, create feature file in the ‘Features’ folder with the name of “MyTest.feature” – Process is similar to creating a folder

Automation Testing Using Cucumber with Selenium

Note: You may need to install the Cucumber Eclipse Plugin for this to work.Goto — Helps->Install New Software->copy paste the link http://cucumber.github.io/cucumber-eclipse/update-site/ and install

Step 4) Write scenarios.

Below lines are written in ‘MyTest.feature’ file using the Gherkin language as shown below:

Feature: Reset functionality on login page of Application Scenario: Verification of Reset button Given Open the Firefox and launch the application When Enter the Username and Password Then Reset the credential

Code Explanation

Line 1) In this line we write business functionality.

Line 2) In this line we write a scenario to test.

Line 3) In this line we define the precondition.

Line 4) In this line we define the action we need to perform.

Line 4) In this line we define the expected outcome or result.

Step 5) Writing selenium testrunner script for Selenium Cucumber framework design

Here we create ‘TestRunner’ package and then ‘Runner.java’ class file under it.

package TestRunner; import org.junit.runner.RunWith; import cucumber.api.CucumberOptions; import cucumber.api.junit.Cucumber; @RunWith(Cucumber.class) @CucumberOptions(features="Features",glue={"StepDefinition"}) public class Runner { }

In the above Cucumber Java example code, we run the cucumber test by using the following annotations:

@RunWith() annotation tells about the test runner class to start executing our tests.

@CucmberOptions() annotation is used to set some properties for our cucumber test like feature file, step definition, etc.

Screenshot of the TestRunner file.

Automation Testing Using Cucumber with Selenium

Step 6) Creating Step Definition script.

Now here we create ‘StepDefinition’ package and then ‘Steps.java’ script file under it. Here we actually write a selenium script to carry out the test under Cucumber methods.

package StepDefinition; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; public class Steps { @Given("^Open the Firefox and launch the application$") public void open_the_Firefox_and_launch_the_application() throws Throwable { System.out.println("This Step open the Firefox and launch the application."); } @When("^Enter the Username and Password$") public void enter_the_Username_and_Password() throws Throwable { System.out.println("This step enter the Username and Password on the login page."); } @Then("^Reset the credential$") public void Reset_the_credential() throws Throwable { System.out.println("This step click on the Reset button."); } }

In the above code, the class is created with the name ‘Steps.’ Cucumber annotation is used to map with feature file. Each annotation method is defined:

@Given annotation define method to open firefox and launch the application

@When annotation define method to enter the username and password

@Then annotation define method to reset the credential

Under each method, we are only printing a message.

Below is the screenshot of the ‘Steps.java’ script and project tree, how it looks like.

Automation Testing Using Cucumber with Selenium

Note: Step definition is nothing but the steps you want to perform under this cucumber method.

Step 7) Executing the Script.

The user can execute this script from Test runner script, i.e. ‘Runner.java’ as shown in below screenshot.

Automation Testing Using Cucumber with Selenium

Step 8) Analyze the output.

On executing the ‘Runner.java’ script, it displays the text on the console. It is the same text defined in ‘Steps.java’ script.

Automation Testing Using Cucumber with Selenium

Scenario 2: Enter login Credential and reset the value.

Here we will just enter Credential on Guru99 demo login page and reset the value

For Scenario 2 we need to update only ‘Steps.java’ script. Here we actually write the selenium script as shown below steps. First, we need to add Selenium jar file to this project.

Automation Testing Using Cucumber with Selenium

Step 1) Here we update the ‘Steps.java’ script as shown in the below code and screenshot.

package StepDefinition; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; public class Steps { WebDriver driver; @Given("^Open the Firefox and launch the application$") public void open_the_Firefox_and_launch_the_application() throws Throwable { System.setProperty("webdriver.gecko.driver", "E://Selenium//Selenium_Jars//geckodriver.exe"); driver= new FirefoxDriver(); driver.manage().window().maximize(); driver.get("http://demo.guru99.com/v4"); } @When("^Enter the Username and Password$") public void enter_the_Username_and_Password() throws Throwable { driver.findElement(By.name("uid")).sendKeys("username12"); driver.findElement(By.name("password")).sendKeys("password12"); } @Then("^Reset the credential$") public void Reset_the_credential() throws Throwable { driver.findElement(By.name("btnReset")).click(); } }

Screenshot of the above selenium script.

Automation Testing Using Cucumber with Selenium

Step 2) Execute the script.

After updating we run the Runner.java.

Step 3) Analyze the output.

In the output you can see the following:

  • Browser launched.
  • Guru99 bank demo site gets opened.
  • Username and password are placed on the login page.
  • Reset the values.

Automation Testing Using Cucumber with Selenium

Scenario 3: Enter login Credential on Guru99 & reset the value. Do this for 3 sets of data.

Here we need to update both the ‘Step.java’ and the feature file.

Step 1) Update the feature file as shown below:

Here we update the feature file with 'Scenario Outline' and 'examples' syntax. Feature: Reset functionality on login page of Application Scenario Outline: Verification of reset button with numbers of credential Given Open the Firefox and launch the application When Enter the Username <username>and Password <password> Then Reset the credential Examples: |username |password | |User1 |password1 | |User2 |password2 | |User3 |password3 | // In this line we define the set of data.

Automation Testing Using Cucumber with Selenium

Step 2) Now update the Step.java script.

Here we update the methods as to pass the parameters, updated script shown below:

package StepDefinition; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; public class Steps { WebDriver driver; @Given("^Open the Firefox and launch the application$") public void open_the_Firefox_and_launch_the_application() throws Throwable { System.setProperty("webdriver.gecko.driver", "E://Selenium//Selenium_Jars//geckodriver.exe"); driver= new FirefoxDriver(); driver.manage().window().maximize(); driver.get("www.demo.guru99.com/v4"); } @When("^Enter the Username \"(.*)\" and Password \"(.*)\"$") public void enter_the_Username_and_Password(String username,String password) throws Throwable { driver.findElement(By.name("uid")).sendKeys(username); driver.findElement(By.name("password")).sendKeys(password); } @Then("^Reset the credential$") public void Reset_the_credential() throws Throwable { driver.findElement(By.name("btnReset")).click(); } }

Automation Testing Using Cucumber with Selenium

Step 3) Now execute the updated script.

Below screen shows the successful execution of the script and time taken by each set of data.

Automation Testing Using Cucumber with Selenium

Step 4) Analyze the output.

In the output you can see the following:

Below output gets repeated for the number of data sets, i.e., 3 sets.

  • Browser launched.
  • Guru99 bank demo site gets opened.
  • Username and password are placed on the login page.
  • Reset the values.

Automation Testing Using Cucumber with Selenium

Conclusion.

Cucumber is a very popular BDD tool. It is easy to read and can be understood by all stakeholders including technical and non-technical person.

Cucumber can be integrated with Selenium using following 3 steps

  1. Create feature file in which define the feature and scenarios step by step using Gherkin language.
  2. Create Testrunner file. In this file, we integrated Cucumber with BDD framework in Selenium. We execute this script.
  3. Creat Step definition, the actual selenium script defined under this package.
Sours: https://www.guru99.com/using-cucumber-selenium.html

Test example cucumber

Keywords

Gherkin uses a set of special keywords to give structure and meaning to executable specifications. Each keyword is translated to many spoken languages; in this reference we’ll use English.

Most lines in a Gherkin document start with one of the keywords.

Comments are only permitted at the start of a new line, anywhere in the feature file. They begin with zero or more spaces, followed by a hash sign () and some text.

Block comments are currently not supported by Gherkin.

Either spaces or tabs may be used for indentation. The recommended indentation level is two spaces. Here is an example:

The trailing portion (after the keyword) of each step is matched to a code block, called a step definition.

Each line that isn’t a blank line has to start with a Gherkin keyword, followed by any text you like. The only exceptions are the feature and scenario descriptions.

The primary keywords are:

There are a few secondary keywords as well:

  • (Doc Strings)
  • (Data Tables)
  • (Tags)
  • (Comments)

Gherkin is localised for many spoken languages; each has their own localised equivalent of these keywords.

Feature

The purpose of the keyword is to provide a high-level description of a software feature, and to group related scenarios.

The first primary keyword in a Gherkin document must always be , followed by a and a short text that describes the feature.

You can add free-form text underneath to add more description.

These description lines are ignored by Cucumber at runtime, but are available for reporting (they are included by reporting tools like the official HTML formatter).

The name and the optional description have no special meaning to Cucumber. Their purpose is to provide a place for you to document important aspects of the feature, such as a brief explanation and a list of business rules (general acceptance criteria).

The free format description for ends when you start a line with the keyword , , or (or their alias keywords).

You can place tags above to group related features, independent of your file and directory structure.

Descriptions

Free-form descriptions (as described above for ) can also be placed underneath /, , and .

You can write anything you like, as long as no line starts with a keyword.

Descriptions can be in the form of Markdown - formatters including the official HTML formatter support this.

Rule

The (optional) keyword has been part of Gherkin since v6.

The keyword is still pretty new. It has been ported in a lot of Cucumber implementation already. Yet if you encounter issues, check the documentation of your Cucumber implementation to make sure it supports it.

The purpose of the keyword is to represent one business rule that should be implemented. It provides additional information for a feature. A is used to group together several scenarios that belong to this business rule. A should contain one or more scenarios that illustrate the particular rule.

For example:

Example

This is a concrete example that illustrates a business rule. It consists of a list of steps.

The keyword is a synonym of the keyword .

You can have as many steps as you like, but we recommend 3-5 steps per example. Having too many steps will cause the example to lose its expressive power as a specification and documentation.

In addition to being a specification and documentation, an example is also a test. As a whole, your examples are an executable specification of the system.

Examples follow this same pattern:

  • Describe an initial context ( steps)
  • Describe an event ( steps)
  • Describe an expected outcome ( steps)

Steps

Each step starts with , , , , or .

Cucumber executes each step in a scenario one at a time, in the sequence you’ve written them in. When Cucumber tries to execute a step, it looks for a matching step definition to execute.

Keywords are not taken into account when looking for a step definition. This means you cannot have a , , , or step with the same text as another step.

Cucumber considers the following steps duplicates:

This might seem like a limitation, but it forces you to come up with a less ambiguous, more clear domain language:

Given

steps are used to describe the initial context of the system - the scene of the scenario. It is typically something that happened in the past.

When Cucumber executes a step, it will configure the system to be in a well-defined state, such as creating and configuring objects or adding data to a test database.

The purpose of steps is to put the system in a known state before the user (or external system) starts interacting with the system (in the steps). Avoid talking about user interaction in ’s. If you were creating use cases, ’s would be your preconditions.

It’s okay to have several steps (use or for number 2 and upwards to make it more readable).

Examples:

  • Mickey and Minnie have started a game
  • I am logged in
  • Joe has a balance of £42

When

steps are used to describe an event, or an action. This can be a person interacting with the system, or it can be an event triggered by another system.

It’s strongly recommended you only have a single step per Scenario. If you feel compelled to add more, it’s usually a sign that you should split the scenario up into multiple scenarios.

Examples:

  • Guess a word
  • Invite a friend
  • Withdraw money

Most software does something people could do manually (just not as efficiently).

Try hard to come up with examples that don’t make any assumptions about technology or user interface. Imagine it’s 1922, when there were no computers.

Implementation details should be hidden in the step definitions.

Then

steps are used to describe an expected outcome, or result.

The step definition of a step should use an assertion to compare the actual outcome (what the system actually does) to the expected outcome (what the step says the system is supposed to do).

An outcome should be on an observable output. That is, something that comes out of the system (report, user interface, message), and not a behaviour deeply buried inside the system (like a record in a database).

Examples:

  • See that the guessed word was wrong
  • Receive an invitation
  • Card should be swallowed

While it might be tempting to implement steps to look in the database - resist that temptation!

You should only verify an outcome that is observable for the user (or external system), and changes to a database are usually not.

And, But

If you have successive ’s, ’s, or ’s, you could write:

Or, you could make the example more fluidly structured by replacing the successive ’s, ’s, or ’s with ’s and ’s:

*

Gherkin also supports using an asterisk () in place of any of the normal step keywords. This can be helpful when you have some steps that are effectively a list of things, so you can express it more like bullet points where otherwise the natural language of etc might not read so elegantly.

For example:

Could be expressed as:

Background

Occasionally you’ll find yourself repeating the same steps in all of the scenarios in a .

Since it is repeated in every scenario, this is an indication that those steps are not essential to describe the scenarios; they are incidental details. You can literally move such steps to the background, by grouping them under a section.

A allows you to add some context to the scenarios that follow it. It can contain one or more steps, which are run before each scenario, but after any Before hooks.

A is placed before the first /, at the same level of indentation.

For example:

is also supported at the level, for example:

You can only have one set of steps per or . If you need different steps for different scenarios, consider breaking up your set of scenarios into more s or more s.

For a less explicit alternative to , check out conditional hooks.

Tips for using Background

  • Don’t use to set up complicated states, unless that state is actually something the client needs to know.
    • For example, if the user and site names don’t matter to the client, use a higher-level step such as .
  • Keep your section short.
    • The client needs to actually remember this stuff when reading the scenarios. If the is more than 4 lines long, consider moving some of the irrelevant details into higher-level steps.
  • Make your section vivid.
    • Use colourful names, and try to tell a story. The human brain keeps track of stories much better than it keeps track of names like , , , and so on.
  • Keep your scenarios short, and don’t have too many.
    • If the section has scrolled off the screen, the reader no longer has a full overview of what’s happening. Think about using higher-level steps, or splitting the file.

Scenario Outline

The keyword can be used to run the same multiple times, with different combinations of values.

The keyword is a synonym of the keyword .

Copying and pasting scenarios to use different values quickly becomes tedious and repetitive:

We can collapse these two similar scenarios into a .

Scenario outlines allow us to more concisely express these scenarios through the use of a template with -delimited parameters:

Examples

A must contain one or more (or ) section(s). Its steps are interpreted as a template which is never directly run. Instead, the is run once for each row in the section beneath it (not counting the first header row).

The steps can use delimited parameters that reference headers in the examples table. Cucumber will replace these parameters with values from the table before it tries to match the step against a step definition.

You can also use parameters in multiline step arguments.

In some cases you might want to pass more data to a step than fits on a single line. For this purpose Gherkin has and .

Doc Strings

are handy for passing a larger piece of text to a step definition.

The text should be offset by delimiters consisting of three double-quote marks on lines of their own:

In your step definition, there’s no need to find this text and match it in your pattern. It will automatically be passed as the last argument in the step definition.

Indentation of the opening is unimportant, although common practice is two spaces in from the enclosing step. The indentation inside the triple quotes, however, is significant. Each line of the Doc String will be dedented according to the opening . Indentation beyond the column of the opening will therefore be preserved.

Doc strings also support using three backticks as the delimiter:

This might be familiar for those used to writing with Markdown.

Whilst all current versions of Cucumber support backticks as the delimiter, many tools like text editors don’t (yet).

Data Tables

are handy for passing a list of values to a step definition:

Just like , will be passed to the step definition as the last argument.

Table Cell Escaping

If you want to use a newline character in a table cell, you can write this as . If you need a as part of the cell, you can escape it as . And finally, if you need a , you can escape that with .

Data Table API

Cucumber provides a rich API for manipulating tables from within step definitions. See the Data Table API reference reference for more details.

The language you choose for Gherkin should be the same language your users and domain experts use when they talk about the domain. Translating between two languages should be avoided.

This is why Gherkin has been translated to over 70 languages .

Here is a Gherkin scenario written in Norwegian:

A header on the first line of a feature file tells Cucumber what spoken language to use - for example for French. If you omit this header, Cucumber will default to English ().

Some Cucumber implementations also let you set the default language in the configuration, so you don’t need to place the header in every file.

Sours: https://cucumber.io/docs/gherkin/reference/
BDD for Beginners 1 - What is BDD with Examples - How BDD works - What is Cucumber

Cucumber.js for BDD: An Introductory Tutorial With Examples

Cucumber.js and BDD aren’t new kids on the block. But they’re still fairly unfamiliar for many developers. That’s unfortunate, because the two can be very powerful tools for both the business people and developers. Let’s have a short look at what BDD is, and then see how Cucumber.js can be used to your advantage.

What Is BDD?

If you’re unfamiliar with BDD, don’t worry. It’s not a difficult topic. BDD is short for behavior driven development. As far as I know, the term was coined by Dan North in 2003 as a reaction to TDD (test-driven development). The lines between TDD and BDD aren’t always clear, and you might even be doing BDD without knowing it.

Basically, BDD means writing automated tests in a language that is meaningful to the business people. So where technical language is OK in TDD, you would want to avoid it in BDD. As an example, you could name a TDD-style test “getPremiumCustomerDiscountTest”, whereas in BDD you would name it something like “givenAPremiumCustomer_WhenWeGetTheDiscount_ItShouldReturnTenPercent.”

Wow! That’s quite a long name. But it does read more like a piece of documentation. A new developer can immediately understand the business rule behind it. You could even write it down as a real sentence and a non-technical user would understand it.

So is the only difference that we just use a readable sentence? Well, yes and no. The difference lies in the fact that we use the language of our end-users, the business or domain language.

BDD will often use a recurring structure in its tests, the given-when-then style of tests.

The “given” part is where you declare preconditions. In our example above we had a premium customer. Next, the “when” part contains the action you want to test. And finally, you verify the outcome in the “should” part.

Expand Your Test Coverage

Fast and flexible authoring of AI-powered end-to-end tests — built for scale.

Start Testing Free

When written in pure code, this can become quite a verbose sentence. For example, what if it’s the premium customer’s birthday and the discount should be higher? You’d have to write something like “givenAPremiumCustomerAndItsTheirBirthday_WhenWeGetTheDiscount_ItShouldReturnTenPercent.” As you can see, this becomes unwieldy when there are more and more preconditions and assertions.

Introducing Cucumber.js

Cucumber.js is a testing library that allows you to write your tests in plain language. It follows the given-when-then structure, but as you’ll see the tests are very readable. Even by business users. This allows your tests to be a point of communication and collaboration. They can even serve as documentation that is automatically up-to-date!

This can have far-reaching consequences. Whenever there is an issue or a feature request, both developers and business people can work on the same document. Developers can then translate this document into a test and implement the feature.

Cucumber.js (and similar tools in other languages) uses something called the Gherkin language. It’s a Domain Specific Language but it’s easily readable. Here’s what a test could look like:

Feature:Automatic discounts forpremium customers

    Premium customers should automatically geta

    discount of10%on purchases over$100.

 

    Scenario:Purchase over$100

        Givenapremium customer

        Andan order containing

            |item   |amount|price|

            |pencil|100    |1     |

            |paper  |1      |35    |

        When the customer checks out

        Thenthe total price should be121.5

See how the words Given, When and Then structure our test? A test in the Gherkin language is called a scenario. And scenario’s are organized into features. The sentence below the “Feature” part (“Premium customers should…”) is just an explanation for the reader. Cucumber.js will ignore this, because the line doesn’t begin with one of the Gherkin keywords like Feature, Scenario, Given, When or Then.

Also note how we can use tables in our tests. This can be a powerful feature when you need a lot of data in your tests. A regular unit test with QUnit or mocha won’t be very readable if it requires a lot of data.

A Sample Application

That’s all fine, but how do we actually get this scenario to run our code?

Let’s start with a sample application. I’ve (partly) followed the Angular Getting Started tutorial and it gives us an app that we can test. You can find the app here. All you need to do is follow the instructions in the readme and you’ll be able to serve it locally.

Of course, you can use Cucumber.js on any application, even applications without a UI. You don’t even have to run it against a full application. It’s entirely possible to test only specific modules, classes or files.

But we’ll be automating the browser and testing our application fully. When you run “ng serve”, you should see an application like this:

Sample-app

Writing and Running Your First Cucumber.js Test

Here’s what we’ll do. We’ll start by writing a scenario in a .feature file. Then we’ll serve our application and we’ll tell Cucumber.js to run the feature file. Cucumber.js will parse the file and call the matching pieces of code.

The Feature File

So let’s write a test first. This is a simple example that fits our sample application:

Feature:Products List

 

    Scenario:Load the products list

        When we request the products list

        Thenwe should receive

            |name           |description                                |

            |Phone XL       |Alarge phone with one of the best screens|

            |Phone Mini     |Agreat phone with one of the best cameras|

            |Phone Standard|                                            |

Notice how we don’t have a “Given” statement? That’s OK, we don’t need it for this test.

Simply save this in a “features” folder and give the file a name. In this case, “products-list.feature” would be a good choice.

Installing and Running Cucumber.js

To run this test, we’ll need Cucumber.js. You can install it as a development dependency by running:

Then, you can run the test by executing:

1

./node_modules/.bin/cucumber-js./features/products-list.feature

You should see some warnings, because we haven’t told Cucumber.js how each step is actually implemented:

Cucumber-warnings

Adding Step Definitions

Luckily, Cucumber.js provides some helpful messages. We need to add some code. These are called “step definitions.” In the “features” folder, create a new “steps” folder. In that folder, create a new file called “productSteps.js”. You could write it in TypeScript, but you would have to transpile the files in the “steps” folder, which is out of scope for this article.

In the step definition file, add this code:

import{When,Then}from'cucumber';

 

When('we request the products list',function(){

    // Write code here that turns the phrase above into concrete actions

    return'pending';

});

 

Then('we should receive',function(dataTable){

    // Write code here that turns the phrase above into concrete actions

    return'pending';

});

As you can see, we now need to implement our steps. But as far as Cucumber.js is concerned, this is enough. If we tell it where our step definitions are located, it will execute these functions. What we do inside those functions, is entirely up to us.

Automating Our Browser

To automate the browser, we need to install Selenium:

1

npmi-Dselenium-webdriver

You’ll also need to install a specific driver for the browser of your choice and add it to your PATH environment variable. You can find the links in the documentation. Be sure to download the version that matches the version of your browser.

Then, change the step definition code to:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

const{When,Then,After}=require('cucumber');

constassert=require('assert');

const{Builder,By,until}=require('selenium-webdriver');

 

When('we request the products list',async function(){

    this.driver=newBuilder()

        .forBrowser('chrome')

        .build();

 

    this.driver.wait(until.elementLocated(By.tagName('h1')));

 

    await this.driver.get('http://localhost:4200');

});

 

Then('we should receive',async function(dataTable){

    varproductElements=await this.driver.findElements(By.className('product'));

    varexpectations=dataTable.hashes();

    for(leti=0;i<expectations.length;i++){

        constproductName=await productElements[i].findElement(By.tagName('h3')).getText();

        assert.equal(productName,expectations[i].name);

 

        constdescription=await productElements[i].findElement(By.tagName('p')).getText();

        assert.equal(description,`Description:${expectations[i].description}`);

    }

});

 

After(async function(){

    this.driver.close();

});

Let’s break this down.

The first block is the “when” block. It defines a function that can be used in a “when” statement in a feature file:

When('we request the products list',async function(){

    this.driver=newBuilder()

        .forBrowser('chrome')

        .build();

 

    this.driver.wait(until.elementLocated(By.tagName('h1')));

 

    await this.driver.get('http://localhost:4200');

});

We’re building a driver first. This will “drive” our browser. It’s the point where we can control the behavior of our browser: find elements, enter text, click links and buttons, etc.

Next, we’re telling the driver to wait until the H1 element has loaded. This is necessary because Angular will need to finish rendering before we can start testing.

As a last step, we’re loading our web page, which we served with the “ng serve” command.

Let’s look at the “then” block:

Then('we should receive',async function(dataTable){

    varproductElements=await this.driver.findElements(By.className('product'));

    varexpectations=dataTable.hashes();

    for(leti=0;i<expectations.length;i++){

        constproductName=await productElements[i].findElement(By.tagName('h3')).getText();

        assert.equal(productName,expectations[i].name);

 

        constdescription=await productElements[i].findElement(By.tagName('p')).getText();

        assert.equal(description,`Description:${expectations[i].description}`);

    }

});

Here, we’re receiving a Cucumber.js datatable. This is the table that you can see in the feature file. We then find the products in our web page and compare it to the corresponding items in the datatable.

The last piece of code in our step definition closes the browser:

After(async function(){

    await this.driver.close();

});

An “After” function will be run after a scenario has finished. This is called a hook and you can also have functions run before scenarios or only for specific scenarios.

Make sure you start the web application first, and then run the test again:

1

./node_modules/.bin/cucumber-js./features/products-list.feature

You will see a browser pop up, and the page load. The test will then assert the products and it will pass:

Cucumber-pass

Moving Further

This was a simple example where we didn’t even interact with the web page. But the structure is clear now:

  • write .feature files with scenarios and a given-when-then structure for each scenario
  • write step definition files where you define functions that match the steps in your scenarios
  • implement these functions as you wish (in our case we used Selenium to automate our browser)
  • run the tests by executing the cucumber-js executable in the node_modules/.bin folder

There is much more that Cucumber.js can do. For example, you can allow parameters in your step definitions, hook into the beginning or end of your scenario or test run, and tag scenarios.

The Real Power of Cucumber.js

Cucumber.js is a powerful testing framework. You can use it for unit, integration or end-to-end tests. But its real power lies in the readable language that defines the test. This allows it to become a piece of collaboration and communication between all invested parties. The tests become the documentation and vice-versa.

This post was written by Peter Morlion. Peter is a passionate programmer that helps people and companies improve the quality of their code, especially in legacy codebases. He firmly believes that industry best practices are invaluable when working towards this goal, and his specialties include TDD, DI, and SOLID principles.

What to read next

TDD vs BDD: A Developer’s Pocket Reference With Examples

A Detailed Introduction and How-To for Javascript BDD

Sours: https://www.testim.io/blog/cucumber-js-for-bdd-an-introductory-tutorial-with-examples/

You will also be interested:

.



1101 1102 1103 1104 1105