How to Create a BDD Automation Framework using Cucumber in Java and Playwright? 

How to Create a BDD Automation Framework using Cucumber in Java and Playwright? 

Behavior Driven Development (BDD) is a process that promotes collaboration between developers, testers, and stakeholders by writing test cases in simple, plain language. BDD Automation Frameworks like Cucumber use Gherkin to make test scenarios easily understandable and link them to automated tests.

In this guide, we’ll show you how to create a BDD Automation Framework using Java and Playwright. Playwright is a powerful browser automation tool, and when combined with Java and Cucumber, it creates a solid BDD testing framework.

Introduction to BDD Automation Framework:

BDD Automation Framewrok

Automation testing is testing software with the latest tools and technologies with developed scripts in less time. In Automation testing it involves test case execution, data validation, and result reporting.

Why Playwright over Selenium? 

Playwright is an open-source Node.js library that further enables efficient end-to-end (E2E) testing of web applications. As Playwright offers better performance speed than Selenium. Also, Playwright offers various features like Cross-Brower support, Multi-platform, Headless and Headful Mode, Async/Await API, Integration with Testing Frameworks. 

What is BDD Automation Framework? 

BDD framework is an agile approach to test software where testers write test cases in simple language so that non-tech person can also understand the flow. Moreover, it enhances collaboration between the technical team and the business team. We use Gherkin language to write feature files, making them easily readable by everyone.

Prerequisites for BDD Automation Framework: 

1. Install JDK

Install the Java environment as per the system compatible.

https://download.oracle.com/java/22/latest/jdk-22_windows-x64_bin.zip

Steps: 

  1. Download JDK: 
    • Go to the Oracle JDK download page
    • First, choose the appropriate JDK version, and then click on the download link for the Windows version.
  2. Run the Installer: 
    • Once the download is complete, run the installer. 
    • To begin, follow the installation instructions, then accept the license agreement, and finally choose the installation directory.
  3. Set Environment Variables: 
    • Open the Control Panel and go to System and Security > System > Advanced system settings. 
    • Click on “Environment Variables”.
    • Under “System Variables,” click on “New” and add a variable named JAVA_HOME with the path to the JDK installation directory (e.g., C:\Program Files\Java\jdk-15). 
    • Find the “Path” variable in the “System Variables” section, click on “Edit,” and add a new entry with the path to the bin directory inside the JDK installation directory (e.g., C:\Program Files\Java\jdk-15\bin).
  4. Verify Installation: 
    • Open a Command Prompt and check if Java is installed correctly by typing `java -version` and `javac -version`.

2. IntelliJ Idea IDE for programming 

https://www.jetbrains.com/idea/download/#section=windows

Steps: 

  1. Download IntelliJ IDEA: 
  2. Run the Installer:
    • Once the download is complete, run the installer. 
    • Follow the installation instructions: 
    • Choose the installation directory. 
    • Select the components you want to install (e.g., 64-bit launcher, .java file association). 
    • Optionally create a desktop shortcut. 
  3. Start IntelliJ IDEA: 
    • After the installation is complete, start IntelliJ IDEA from the Start menu or desktop shortcut. 
    • Follow the initial setup wizard to customize your IDE (e.g., theme, plugins). 

3. Maven 

https://maven.apache.org/download.cgi

Steps: 

  1. Download Maven: 
    • Go to the Apache Maven download page
    • Click on the link to download the binary zip archive (e.g., apache-maven-3.x.y-bin.zip). 
  2. Extract the Archive: 
    • Extract the downloaded zip file to a suitable directory (e.g., C:\Program Files\Apache\maven). 
  3. Set Environment Variables: 
    • Open the Control Panel and go to System and Security > System > Advanced system settings. 
    • Click on “Environment Variables”.
    • Under “System Variables”, click on “New” and add a variable named MAVEN_HOME with the path to the Maven installation directory (e.g., C:\Program Files\Apache\maven\apache-maven-3.x.y). 
    • Find the “Path” variable in the “System Variables” section, click on “Edit”, and add a new entry with the path to the bin directory inside the Maven installation directory (e.g., C:\Program Files\Apache\maven\apache-maven-3.x.y\bin). 
  4. Verify Installation: 
    • To check if Maven is installed correctly, open a Command Prompt and type `mvn -version`.

4. Cucumber 

https://mvnrepository.com/artifact/io.cucumber/cucumber-java/7.11.0

Prerequisites

  • Java Development Kit (JDK): Ensure you have JDK installed and properly configured. 
  • Maven or Gradle: Depending on your preference, however, you’ll need Maven or Gradle to manage your project dependencies. 

Steps to Install Cucumber with Maven 

  1. Create a Maven Project: 
  2. Update pom.xml File: 
    • Open the pom.xml file in your project. 

This Maven POM file (pom.xml) defines project metadata, dependencies on external libraries (Cucumber, Selenium, Playwright), and Maven build properties. It provides the necessary configuration for managing dependencies, compiling Java source code, and integrating with Cucumber, TestNG, Selenium, and Playwright frameworks to support automated testing and development of the CalculatorBDD project. 

Project Setup or BDD Automation Framework:

Before starting the project on the BDD Automation Framework: 

  • Create a new Maven project in your IDE.
  • Add the dependencies in Pom.xml file .
  • Create folder structure following steps given below: 
Folder Structure

When we created the new project for the executable jar file, we could see the simple folder structure provided by Maven.  

  1. SRC Folder: The SRC folder is the parent folder of a project, and it will also include the main and test foldersIn the QA environment, we generally use the test folder, while we reserve the main folder for the development environment. The development team uses the main folder, so the created JAR contains all the files inside the src folder.
  2. Test Folder: Inside the test folder; additionally, Java and resources folders are available.  
  3. Java Folder: This folder primarily contains the Java classes where the actual code is present. 
  4. Resources Folder: The Resources folder contains the resources file, test data file, and document files. 
  5. Pom.xml: In this file, we are managing the dependencies and plugins that are required for automation.

As our project structure is ready so we can start with the BDD framework: 

1. Feature file: 

Here we have described the scenario in “Gherkin” language which is designed to be easily understandable by non-technical stakeholders as well as executable by automation tools like Cucumber. Each scenario is written in structured manner using keywords “Given”, “When” and “Then”. Calculator.feature in this we have specifically written our functional testing steps. 

2. Step Def File: 

The step definition file serves as the bridge between actual feature file with the actual method implementation in the page file. The Calculator steps are a step definition file that maps the feature file to the page file and functional implementation.

3. Page File:

Page file, in addition, is actual code implementation from the step definition file.Here, we have saved all the actual methods and web page elements, thereby ensuring easy access and organization. It is basically POM structure. So here we are performing addition operation in Calculator we application so created a method to click on a number and another method for clicking on the operator. Here we can minimize the code by reusing the code as much as possible. 

4. Hooks: 

Hooks are setup and teardown methods that, therefore, are written separately in the configuration class. Here we have annotation declare in the hooks file @before and @After. Hooks are steps to be performed a before and after function of the feature file. In this we have open the Web browser in Before and After Tag. These are special functions which allows the testers to execute specific points during execution. 

5. TestContext: 

The TestContext class, moreover, holds various instances and variables required for test execution. In this context, we have successfully created a web driver instance, a page file instance, and a browser context. As a result, the code reusability, organization, and maintainability are improved here.

6. TestRunner: 

The Test Runner is responsible for discovering test cases, executing them, and reporting the results back; additionally, it provides the necessary infrastructure to execute the tests and manage the testing workflow. It also syncs the feature file with step file. 

7. WebUtils:

Web Utils is a file in which browser instance is created and playwright is initialised here. The code for web browser page launching is written here and for closing the browser instance. The page is extended by TestContext where all the properties of TestContext are given to WebUtils page. 

This is the important file where we download all the dependencies required for the test execution. Also, it contains information of project and configuration information for the maven to build the project such as dependencies, build directory, source directory, test source directory, plugin, goals etc. 

This are the dependencies required to download: 

https://mvnrepository.com/artifact/io.cucumber/cucumber-java
https://mvnrepository.com/artifact/io.cucumber/cucumber-testng
https://mvnrepository.com/artifact/com.microsoft.playwright/playwright

Conclusion: 

In this blog, we’ve discussed using the Java Playwright framework with Cucumber for BDD. Playwright offers fast, cross-browser testing and easy parallel execution, making it a great alternative to Selenium. Paired with Cucumber, it helps teams write clear, automated tests. Playwright’s debugging tools and test isolation also reduce test issues and maintenance, making it ideal for building reliable test suites for faster, higher-quality software delivery. 

GitHub Link – https://github.com/spurqlabs/PlaywrightJavaBDD

Click here to read more blogs like this.

How to Automate tests using Taiko with Cucumber in JavaScript

How to Automate tests using Taiko with Cucumber in JavaScript

Hello! In this blog, I will be exploring how to automate tests using Taiko with Cucumber in JavaScript. The Taiko tool is easy to automate and is very reliable, and it works faster to execute and run test cases. It is a user-friendly tool as well. 

What is Takio?

A Taiko is an automation tool that is available for free and it is an open-source browser automation tool. It is built by the ThoughtWorks team. It uses the Node.js library to automate the chrome browser. Taiko is very useful to create maintainable and highly readable JavaScript tests.  

Taiko Features:

The Taiko was explicitly built to test modern web applications. 

The features of Taiko that set it apart from other browser automation solutions are listed below.

  1. Easy Installation
  2. Interactive Recorder
  3. Smart Selectors
  4. Handle XHR and dynamic content
  5. Request/Response stubbing and mocking

We can use Taiko on three platforms:

  1. Windows
  2. macOS
  3. Linux

How to install Taiko?

A Taiko is available on npm: You can use the following NPM command to install the taiko on your system.

npm install -g taiko

What is cucumber?

A Cucumber is a testing tool that allows BDD.  It offers a way to write tests that everyone, regardless of technical ability, can follow. Before developers build their code in BDD, users (business analysts, product owners) first write scenarios or acceptance tests that describe the system behavior from the perspective of the customer. Such scenarios and acceptance tests then are reviewed and approved by the product owners.

How to install Cucumber?

Basically, cucumber is available on npm: You can use the following NPM command to install the cucumber on your system.

npm install --save-dev @cucumber/cucumber

Getting Started 

We will be using Visual Studio code to write our test automation code in JavaScript. We will create a feature file first, then click on the left side of the panel and choose “new file” from the menu that appears. Give a file name after that, such as the Calculator. feature

I’ll start out by introducing the Taiko framework, which integrates BDD and Cucumber. You will be guided through the code in the next step.

Feature: Calculator operations
  @smoke
  Scenario: Addition of 2 numbers
    Given I launch calculator application
    When I click on number 2
    And I click on operator +
    And I click on number 2
    Then I verify the result is 4

I’ll describe how to automate the calculator page in this place. The code shown below builds calculator steps where we must import statements provided by cucumber before navigating to the support folder. 

After that, we can import the cucumber and assertion statements and that will build a page where all the steps are generally placed. 

Basically, this is the step definition file where we need to map the feature file steps and call methods declared in the page file.

After that, we have to import the page file in the step definition file.  And we need to call the methods declared in the page file. 

Following is the code snippet for the step definition file.

const { Given, When, Then } = require('@cucumber/cucumber')
const calculate = require('../../pages/calculatorPage')
Given('I launch calculator application', async function () {
  await new calculate().launch()
})
When('I click on number {string}', async function (num) {
  await new calculate().click_number(num)
})
When('I click on operator {string}', async function (num) {
  await new calculate().click_operator(num)
})
Then('I verify the result is {string}', async function (num) {
  await new calculate().verify_result(num)
})

Now let’s create a page(We are using Page Object Model (POM) structure here) file where we have to declare the class and all the methods cleaning in step definitions.

Following is the code snippet for the page file.

const { Before } = require('@cucumber/cucumber')
var { setDefaultTimeout } = require('@cucumber/cucumber')
setDefaultTimeout(60 * 1000)
const {
  openBrowser,
  goto,
  write,
  click,
  $,
  closeBrowser,
  setConfig,
  button,
  waitFor,
} = require('taiko')
const assert = require('assert')
setConfig({ observeTime: 30000, retryTimeout: 30000, navigationTimeout: 30000 })
class calculate {
  async launch() {
    await openBrowser({ headless: false })
    return goto('calculator.net')
  }
  async click_number(num) {
    waitFor(5000)
    await click($('span[onclick="r(' + num + ')"]'))
  }
  async click_operator(num) {
    await click($(`span[onclick="r('` + num + `')"]`))
  }
  async verify_result(num) {
    waitFor(5000)
    assert.equal(await $('#sciOutPut').text(), num)
    closeBrowser()
  }
}
module.exports = calculate

And, In the above code snippet, methods contain actions like opening the browser, visiting a website, CSS selectors and actions to be performed on it (click), and Assertions. You may notice that we are doing open browser and close browser actions into this page file itself which is not the best practice. You can move it to Before/After hooks and create a nice framework. However, that is for a later blog 🙂

So, to execute the test case, you can run the following command from the terminal.

npx cucumber-js --publish

Happy testing !!!

Conclusion:

We can automate tests using taiko with Cucumber with JavaScript very easily. Taiko is a very powerful tool and easy to implement. It will definitely compete with Selenium and Playwright in the coming years.

Read more blogs here

Capture screenshots and videos in java playwright

Capture screenshots and videos in java playwright

Any test automation report, without screenshots, would look dull and will not provide enough information on where the test failed. If you add only screenshots, it will make the report information-rich. Now, if your tool has the capability to record the video as well, then it will be cherry on the top. A playwright is an automation tool that has these features integrated in-built. Here we will cover various types of screenshots that can be attached and how to record the video. This blog will help you to learn the steps to include Capture screenshots and videos in java playwright.

  • Playwright contains the following inbuilt functionalities:

Here, we are exploring the functionality to capture the snapshots and how to attach them to the Cucumber report. You must have the Cucumber report set up in your framework in order to accomplish this.

Let’s, Understand first how to Capture screenshots and videos in java playwright.

1. Page Screenshot:

As you are all aware, we usually use this screenshot to attach what is visible on the screen for verification purposes.

public static List takeScreenShots() throws IOException 
    {
	public static byte[] array;
        long millisStart = Calendar.getInstance().getTimeInMillis();
        array = page.screenshot(new Page.ScreenshotOptions().setFullPage(false).setPath(Paths.get("test-output/ScreenShots/" + millisStart + ".png")));
        List output = new ArrayList();
        output.add(array);
        output.add(millisStart + ".png");
        return output;
    }

2. Full Page Screenshot:

If your test requires you to attach a screenshot of the entire page, top to bottom. So this method will guide you easily. The code below helps to take a snapshot of the entire page, no matter how long it is, because setFullPage is set to ‘true’.

public static List takeScreenShots() throws IOException
    {
	public static byte[] array;
        long millisStart = Calendar.getInstance().getTimeInMillis();
        array = page.screenshot(new Page.ScreenshotOptions().setFullPage(true).setPath(Paths.get("test-output/ScreenShots/" + millisStart + ".png")));
        List output = new ArrayList();
        output.add(array);
        output.add(millisStart + ".png");
        return output;
    }

However, now you can see that the full scrollable page has been captured in this step.

3. Element Screenshot:

So here, now you can also capture a screenshot of a specific element with the help of a playwright. In the below code, you can see that a locator path is sent as a parameter to the .screenshot() method.

page.locator("locator of that element").screenshot(new Locator.ScreenshotOptions().setPath(Paths.get("test-output/ScreenShots/screenshot.png")));

Here, we can see that the screenshot has captured only the element given in the locator.

4. Attaching Screenshot to Cucumber Report:

Now, we are going to discuss how to attach these screenshots to the cucumber report.

The first step is to set up your framework for the cucumber report, and this blog does a great job of explaining how to do that. This will allow you to add a screenshot to the Cucumber report using the code below. In general, this code is placed in your after hooks (AfterScenario, AfterStep, After). In the code below, I recently added a current millisecond time as the file name. However, you can customize the file names to your choice. 

public void screenshots(Scenario scenario) throws IOException 
    {
        WebUtil.takeScreenShots();
        long millisStart = Calendar.getInstance().getTimeInMillis();
        scenario.attach(array, "image/png",millisStart+".png" );
    }

Therefore, you can now view the Cucumber report with the screen attach to the report. while you click on the expand icon, You may see the screenshot as well.

5. Video Recording:

Now, here the playwright has the ability to record the video which will make it easier for the tester to understand their execution results. Then we’ll see how you fit that video into your report.

First, you must declare the context properties on your browser as shown in the below code. Or, you can simply update your context option where you can begin your context on the browser. Typically this method is called inside Before hooks.

public static BrowserContext RecordVideo() throws IOException 
    {
        return browserContext = browser.newContext(new Browser.NewContextOptions().setRecordVideoDir(Paths.get("test-output/RecordedTestCase/")));
    }

Now the above code will help you to record the video and it’s going to execute the test. After that, it will automatically be stored on the path which is shown in the code. Moreover, you must see that the context of your browser is closed after it will be stored.

The below lines of code demonstrate how to convert a recorded video into bytes. These bytes can then be used to attach the recorded video to a report or perform other operations.

public static byte[] encodeVideo(Path path) throws IOException {
    FileInputStream fis = new FileInputStream(String.valueOf(path));
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    byte[] b = new byte[1024];

    for (int readNum; (readNum = fis.read(b)) != -1; ) {
        bos.write(b, 0, readNum);
    }

    byte[] bytes = bos.toByteArray();
    return bytes;
}

After recording it from your project structure, you must use the following code to attach the video to the cucumber report. The tearDown method’s execution video attaching code is described below. This code will be easier to perform once the tearDown method has been completed and your video has been recorded and attached to the report. Normally, this teardown method is written using After hooks.

    public void tearDown(Scenario scenario) throws IOException 
    {
            browserContext.close();
            Path path = page.video().path();
            scenario.attach(WebUtil.encodeVideo(path),"video/webm", scenario.getName()+".webm");
	    browser.close();
            playwright.close();
    }

Now, the screenshots and videos will appear in the cucumber report as shown in the picture below. This video will be available as part of the report.

Conclusion:

Here, we see that the playwright automation tool allows us to take several screenshots as needed. How to record Capture screenshots and videos in java playwright which can help you to identify failures’ underlying causes without having to look at the report itself.

Read more blogs here