Converting PDF to JSON in Java for Test Automation

Converting PDF to JSON in Java for Test Automation

Working with PDF documents programmatically can be a challenging task, especially when you need to extract and manipulate text content. However, with the right tools and libraries, you can efficiently convert PDF text to a structured JSON format.

Converting PDF to JSON programmatically offers flexibility and customization, especially in dynamic runtime environments where reliance on external tools may not be feasible. While free tools exist, they may not always cater to specific runtime requirements or integrate seamlessly into existing systems.

Consider scenarios like real-time data extraction from PDF reports generated by various sources. During runtime, integrating with a specific tool might not be viable due to constraints such as security policies, network connectivity, or the need for real-time processing. In such cases, a custom-coded solution allows for on-the-fly conversion tailored to the application’s needs.

For Example:

  • E-commerce Invoice Processing: Extracting invoice details and converting them to JSON for real-time database updates.
  • Healthcare Records Management: Converting patient records to JSON for integration with EHR systems, ensuring HIPAA compliance.
  • Legal Document Analysis: Extracting specific clauses and dates from legal documents for analysis.

Free tools are inadequate for real-time, automated, and secure PDF to JSON conversion. Coding your own solution ensures efficient, scalable, and compliant data handling.

In this blog, we’ll walk through a Java program that accomplishes using the powerful iTextPDF and Jackson libraries. Screenshots will be included to illustrate the process in Testing.

Introduction for Converting PDF to JSON in Java

PDF documents are ubiquitous in the modern world, used for everything from reports and ebooks to invoices and forms. They provide a versatile way to share formatted text, images, and even interactive content. Despite their convenience, PDFs can be difficult to work with programmatically, especially when you need to extract specific information from them.

Often, there arises a need to extract text content from PDFs for various purposes such as:

  • Data Analysis: Extracting textual data for analysis, reporting, or further processing.
  • Indexing: Creating searchable indexes for large collections of PDF documents.
  • Transformation: Converting PDF content into different formats like JSON, XML, or CSV for interoperability with other systems.

JSON (JavaScript Object Notation) is a lightweight data interchange format that’s easy for humans to read and write, and easy for machines to parse and generate. It is widely used in web applications, APIs, and configuration files due to its simplicity and versatility.

In this guide, we will explore how to convert the text content of a PDF file into a JSON format using Java. We’ll leverage the iTextPDF library for PDF text extraction and the Jackson library for JSON processing. This approach will allow us to take advantage of the structured nature of JSON to organize the extracted text in a meaningful way.

Prerequisites for Converting PDF to JSON in Java

Before we dive into the code, ensure you have the following prerequisites installed and configured:

  1. Java Development Kit (JDK)
  2. Maven for managing dependencies
  3. iTextPDF library for handling PDF documents
  4. Jackson library for JSON processing

Step-by-Step Installation and Setup for Converting PDF to JSON in Java

Install Java Development Kit (JDK)

The JDK is a software development environment used for developing Java applications. To install the JDK:

  • Visit the Oracle JDK download page.
  • Download the appropriate installer for your operating system (Windows, macOS, or Linux).
  • Follow the installation instructions provided on the website.

Verify the installation by opening a command prompt or terminal and typing:

java -version

You should see output indicating the version of Java installed.

Convert pdf to json - 1

Install Maven

Maven is a build automation tool used primarily for Java projects. It helps manage project dependencies and build processes. To install Maven:

  • Visit the Maven download page.
  • Download the appropriate archive file for your operating system.
  • Extract the archive to a directory of your choice.
  • Add the bin directory of the extracted Maven folder to your system’s PATH environment variable.

Verify the installation by opening a command prompt or terminal and typing:

mvn -version

maven version

Download IntelliJ IDEA

  1. Visit the Official Website: Go to the JetBrains IntelliJ IDEA download page.
  2. Step 2: Install IntelliJ IDEA on Windows
  3. Start IntelliJ IDEA: Open from the start menu (Windows).
  4. Complete Initial Setup: Import settings or start fresh.
  5. Start a New Project: Begin a new project or open an existing one.

Open IntelliJ IDEA:

Launch IntelliJ IDEA on your computer

Create or Open a Project

  • If you already have a project, open it. Otherwise, create a new project by selecting File > New > Project….
  • Name your project and select the project location
  • Choose Java from Language.
  • Choose Maven from the Build systems.
  • Select the project SDK (JDK) and click Next.
  • Choose the project template (if any) and click Next.
  • Then click Create.
Open project to convert pdf to json

Create a New Java Class

  • In the Project tool window (usually on the left side), right-click on the (src → test → java) directory or any of its subdirectories where you want to create the new class.
  • Select New > Java Class from the context menu.

Name Your Class

  • In the dialog that appears, enter the name of your new class. For example, you can name it PdfToJsonConversion.
  • Click OK/Enter.
pdf to json conversion
java file

Add the following dependencies to your pom.xml file for Converting PDF to JSON in Java:

json file

Write Your Code to Convert PDF to JSON in Java

  • IntelliJ IDEA will create a new .java file with the name you provided.
  • You can start writing your Java code inside this file. 

The Java Program to Covert PFT to JSON

Here is the complete Java program that converts a PDF file to JSON:

testing.json file

Explanation

Let’s break down the code step by step:

1. Dependencies

Jackson Library:

ObjectMapper, SerializationFeature, ArrayNode, ObjectNode: These are from the Jackson library, used for creating and manipulating JSON objects.

iText Library:

PdfDocument, PdfPage, PdfReader, PdfTextExtractor: These classes are from the iText library, used for reading and extracting text from PDF documents.

TestNG Library:

@Test: An annotation from the TestNG library, used for marking the convertPdfFileToJson method as a test method.

Java Standard Library:

File, IOException, ArrayList, List: Standard Java classes for file operations, handling exceptions, and working with lists.

2. Test Annotation

The class PdfToJsonConversion contains a static method convertPdfFileToJson which is annotated with @Test, making it a test method in a TestNG test class.

3. Method convertPdfFileToJson:

This method handles the core functionality of reading a PDF and converting its content to JSON.

4. Input and Output Paths:

inputPdfPath specifies the PDF file location, and outputJsonPath defines where the resulting JSON file will be saved.

5. PDF to Text Conversion:

  • Create a PdfDocument object using a PdfReader for the input PDF file.
  • Get the number of pages in the PDF.
  • Loop through each page, extract text using PdfTextExtractor, and add the text to contentList.
  • Handle any IOException that may occur.

6. Creating JSON Objects:

  • Create an ObjectMapper for JSON manipulation.
  • Enable pretty printing with SerializationFeature.INDENT_OUTPUT.
  • Create an ArrayNode to hold the content of each page.

7. Adding Page Content to JSON:

  • Iterate over contentList to process each page’s content.
  • For each page, create an ObjectNode and set the page number.
  • Split the page content into lines, then create another ObjectNode to hold each line with its number as the key.
  • Add the linesObject to the pageNode and then add the pageNode to pagesArray.

8. Writing JSON to File

  • Create a File object for the output JSON file.
  • Use the ObjectMapper to write pagesArray to the JSON file, handling any IOException.
  • Print a confirmation message indicating the completion of the process.

9. Output

The program outputs the name of the JSON file once the conversion is complete.

Running the Program

To run this program, ensure you have the required libraries in your project’s classpath. You can run it through your IDE or using a build tool like Maven.

  1. Open your IDE and load the project.
  2. Ensure dependencies are correctly set in your pom.xml.
  3. Run the test method convertPdfFileToJson.

You should see output similar to this in your console: Content stored in What is Software Testing.json. The JSON file will be created in the specified output path.

JSON Output Example

Here’s a snippet of what the JSON output might look like.

Output

Conclusion

Converting PDF text content to JSON can greatly simplify data processing and integration tasks. With Java, the iTextPDF, and Jackson libraries, this task becomes straightforward and efficient. This guide provides a comprehensive example to help you get started with your own PDF to JSON conversion projects.
https://github.com/mangesh-31/PdfToJsonConversion

Click here to read more blog like this.

Effective Locator Strategy for Mobile App Automation using Appium

Effective Locator Strategy for Mobile App Automation using Appium

Introduction:

Mobile App Automation using Appium involves various ways to locate elements for effective testing. In this blog, we’ll se the Mobile app automation Using Appium Inspector, we can inspect elements on both iOS and Android devices.

Now we’ll go for locating the Android Element

  • Mobile App Testing tools are available in the market right now are as follows:
    • Katalon
    • Appium
    • Espresso
    • XCTest
    • Robotium
    • Selndroid
    • Flutter
    • Robot Framework
    • iOS-driver
    • Xamarin

So currently we are going to Inspecting the Locator Strategy for Mobile App Automation using Appium, For the initial setup of Appium for Android device you can refer this blog How To Configure Our System For Real Mobile App Automation. This  blog will guide you for the mobile app automation using Appium setup on Android device.

We have various ways to locate the elements for mobile app automation using Appium Inspector, mainly we have the following ways to locate the elements:

  • Id
  • Xpath
  • Customized Xpath
  • Accessible Id

First, we’ll see how to locate the specific element for Mobile App Automation using Appium

After starting the session on an Android phone you will see the below Appium inspector window

Mobile App Automation - 1

In this image, you can see the mobile screen, App source, and Selected Element tabs.

When you select the particular element on the mobile screen displayed on Appium Inspector, You will see the below image, I have selected the C button from a calculator for mobile app automation using appium.

Mobile App Automation using Appium - 2

Now we can see the DOM content is loaded in the App Source tab, and the Attributes and values will be displayed in the Selected Element tab.

Now we’ll see how to locate the element from the Selected Element tab.

Select Element

In the above image you can see the attribute and values to locate the element

Now we can see the Locator strategies to locate this element for mobile app automation using appium. First, we’ll see locating the element using the Id

First, we’ll have to see the available Attributes for that particular element and then try to locate the element. So copy the ID from given Selected Element tab as shown below

Copied-id

So now We’ll see how to check whether the Id is a valid locator or not.

  • For that first click on the Search bar
Search Bar
  • Then make sure you have selected the correct locator Strategy as shown in the below image.
search for element
  • Now after clicking on the search element, you will get to see the identified element as shown in the below image
Mobile App automation using appium. -3
  • As the element is getting highlighted it indicated that we can use that ID to locate that particular element

Now we’ll see locating elements using XPath for Mobile App Automation using Appium

In a similar way to Id we can locate the element using Xpath, So for first we need to click on the Xpath shown in the below image.

Mobile App Automation using Appium-4

Now click on the search button explained above

XPath

Make sure that you have selected the XPath as Locator Strategy as shown. Then Paste the copied XPath in the Selector Box and click on the Search Button, so then you can see the below image the element is located by the XPath

Locate XPath

The element is getting highlighted and that means we can use this XPath to locate this element

Now we’ll see how to use customized XPath for Mobile App Automation

This allows us to handle parameterization and overcome limitations when ID or XPath is not available by default. So for that, we need to know how we can create XPath

  • The first step is you need to find the class for that particular element
Mobile App AUtomation-5
  • As you can see the above image, class is present for that particular element. So first step is we need to copy this class value
  • The next step is to choose the attribute you want to use the value of.
Mobile App Automation-6
  • These are the various attributes you can use to customize XPath
  • So after that, you can create the Customized XPath, So here is a sample XPath I have used to locate the equal button from the Calculator app
  • In this XPath, I have chosen text attribute. So in the below image, you can see the combination of class and attribute and value. This is how we can create customized XPath
XPath Mobile App Automation
  • As shown in the below image you can see the Located element
Located Elements
  • So when the requirement is there to create a parameterized locator or ID is not available, at that time you can use Customized XPath

For accessibility Id you can follow similar steps like ID to locate the element. The only condition is Accessibility ID should be available for that particular element

Now we’ll go for locating the iOS element for Mobile App Automation using Appium

For iOS automation We’ll be going to see how we can locate the element. To locate elements on iOS devices following strategies are available

  • Accessibility Id
  • XPath
  • Customized XPath

Now we’ll see how to locate the element using Accessibility ID on iOS device.

For that, we’ll have to start the Appium Session on iOS. After starting the Appium session on iOS device you  will get to see the below window of Appium inspector

Appium Inspector

This will be the home page of the calculator on the iOS App. On this screen, you can see three windows Mobile screen, App Source, and Selected  Element. When you select any of the elements displayed on the Mobile screen the screen will be shown below.

Mobile Screen

In the above Image, I have selected the AC button which is for All Clear. After selecting that element the DOM content is loaded in the App Source window and in the Selected Element window we can see the attributes and values that can be used for inspecting the elements.

We have so many options to locate the element as you can see in the Selected Element window. We have accessibility ID, XPath, and customized XPath for Mobile App Automation using Appium.

Now we’ll see how to locate the element using accessibility id for Mobile App Automation using Appium

So first we’ll go to search for element as shown in the below image

Element Search

As shown in the above image you can see that I have selected Locator Strategy as the Accessibility ID and the value I have passed the accessibility ID got from the Selected Element window. Now, I’ll click on the Search button.

The system will display the result window below.

Search Button

As shown in the screenshot, the AC button is highlighted after successfully finding the window element. The count for the found element is 1, and you can use this accessibility ID to locate this specific element.

Note: So for locating the elements using XPath and customized XPath you can refer the steps mentioned for Android.

  • Preffered Locator Strategy: As you can see the Selected element window, We have multiple options to locate the element for Mobile App Automation. So there might be a confusion to select the correct locator strategy. So here are some key points which you can consider while choosing the locator strategy
    • Most preferred locator strategy will be id (Android) or accessibility id (iOS). Because id’s are designed to be unique for direct access.
    • name locator strategy can be used if the particular element have the unique name which can be used to locate element.
    • The XPath are more likely to use if id not available or we have requirement to create locator which needs to be parameterized.

Conclusion:

As we see, we have multiple ways to locate the elements on the Mobile Application. Here in this blog, we got to know the the locator strategies to locate the elements on Android and iOS Application for Mobile App Automation using Appium. So you have multiple options to locate the elements, From which you have to decide which strategy suits best for your requirements. So as mentioned above id is fastest way to locate elements, But you have choice to use XPath and customized XPath for parameterization. https://github.com/appium/appium-inspector/releases

Overall, this blog provides an overview of how to locate elements Mobile App Automation using Appium Inspector. Additionally, it explains the various locator strategies you can choose based on the requirements of your test script.

How to configure Windows Desktop for Android App Automation using Appium?

How to configure Windows Desktop for Android App Automation using Appium?

Setting up Appium for testing on real devices for android app automation can be tricky. Many testers struggle with installing the right software, setting environment variables, and connecting their devices properly. These issues can cause a lot of frustration and slow down the testing process. 

In this blog, we’ll make it easy for you. We’ll walk you through each step, from installing necessary software like the Java Development Kit (JDK) and Android Studio, to setting up your Android device for android app automation. We’ll also show you how to install Appium, configure it correctly, and use tools like Appium Inspector to interact with your app. 

By following this simple guide, you’ll be ready to test your mobile apps on real devices quickly and efficiently. 

What is Appium testing in Android App Automation

Appium is an open-source automation tool used for testing mobile applications. It allows testers to automate native, hybrid, and mobile web applications on iOS and Android platforms using the WebDriver protocol. Appium provides a unified API (Application Programming Interface) that allows you to write tests using your preferred programming language (such as Java, Python, JavaScript, etc.) and test frameworks. It supports a wide range of automation capabilities, including gestures, device rotation, multi-touch actions, and handling various types of mobile elements. Appium enables cross-platform testing, where the same tests can be executed on multiple devices, operating systems, and versions, providing flexibility and scalability in mobile app testing or android testing. 

Advantages of Using Appium in Android App Automation: 

  1. Appium is an open source and free tool available for testers and developers. 
  1. Appium supports both real device and emulators/simulators testing.
  1. Appium is compatible with popular testing frameworks and tools, making it easy to integrate into existing testing workflows and environments.

Advantages of using real device for Android App Automation: 

  1. Real device allows you to check your application under different network like 2G,3G,4G and 5G.
  1. Using real device we can test hardware specific features like GPS, fingerprint and camera.
  1. Using a real device provides more accuracy by taking some factors into consideration like device battery, processor, memory and device size. 

Step→1 

Install Java Development Kit (JDK): 

  • Set JAVA_HOME as environment variable.
Step-1-1-Image Android App Testing
  • Also add jdk’s bin folder path in Path environment variable.
Step-1-2-Image Android app

Step→2 

Install Android Studio: 

  • After successful installation now we will set the ANDROID_HOME environment variable.
Step-2-1-Image
  • Also put platform tools path in path variable.
Step-2-2-Image automation
  • Now open cmd and run adb  in command line and it should get executed successfully. 
Step-2-3-Image

Step→3 

Install Node.js: 

  • If you haven’t already installed Node.js, you can download and install it from the official Node.js website. 
  • Once the installation is complete check node version using command node -v also npm -v.

Step→4 

Install Appium for real device testing using command npm install -g appium in command line:

  • Verify appium version using appium -v  in command line.
  • Now run the command appium  in command line using this command your server should start and we are ready to do testing.
Step-4-1-Image Android app automation

Step→5

Install Appium for real device testing using command npm install -g appium in command line:

  • Now run appium-doctor  in command line to check weather every dependency required for appium has been installed successfully.
Step-5-1-Image Android app automation

Step→6 

Now we need to install UIAutomator driver which allows to interact with the UI elements of Android apps during automated testing. It provides improved stability and performance compared to the original UIAutomator driver. To install it use this command appium driver install uiautomator2  in command line.

Step→7 

Now for real device testing we also need to make some changes on device side too so we need to enable  developer option for this:

  • Open setting and click on about phone.
Stedp-7-1-Image
  • Click on software information.
  • Click on Build number 5 times to enable developer mode.
Step-7-2-Image
  • Now once this option is enabled we need to enable usb debugging option as well.
Step-7-3-Image Android App Automation

Note: Above information to enable the developer mode its for SAMSUNG device it will be different for other device type.

What is Appium Inspector in Android App Testing?

Appium inspector is a tool which provides testers with a graphical user interface  for inspecting and interacting with elements within mobile applications.

Step→8 

Install appium inspector for windows using below link  appium inspector.

Step→9

Start the appium session using command appium -a 127.0.0.1 -p 4723

Step-9-1-Image
  • Alternatively we can use appium GUI  Appium GUI to start the server 

i. Enter the host as 127.0.0.1 

ii. Enter port number as 4723

Step-9-2-Image Android

iii. If you are using Appium GUI for start server.we need to also add remote path for Appium inspector

Step-9-3-Image

Step→10

Open the appium inspector enter remote host as 127.0.0.1 and port as 4723.

Step-10-1-Image

Configuring Desired Capabilities using Appium for Android App Automation: 

When setting up automation with Appium for Android devices, it’s crucial to define the desired capabilities appropriately. These capabilities act as parameters that instruct Appium on how to interact with the device and the application under test. 

deviceName: This parameter specifies the name of the device being used for testing. It’s essential to provide an accurate device name to ensure that Appium connects to the correct device. 

udid: The Unique Device Identifier (UDID) uniquely identifies the device among all others. Appium uses this identifier to target the specific device for automation. Make sure to input the correct UDID of the device you intend to automate. 

platformName: Here, the platform name is set to “Android,” indicating that the automation is targeted towards the Android platform. 

platformVersion: This parameter denotes the version of the Android platform installed on the device. 

automationName: Appium supports multiple automation frameworks, and here, “UiAutomator2” is specified as the automation name. UiAutomator2 is a widely used automation framework for testing Android apps. 

appPackage: The app package is the unique identifier for the application under test. It’s essential for Appium to know which app to launch and interact with during automation.  

appActivity: This parameter specifies the main activity of the application that needs to be launched. 

  • For device udid run adb device command  in command line 
  • For device name and version we can check software information from android settings 
  • For application package and appActivity we can download Apk Info application from play store 
appActivity-1 Android App
  • For application bundle Id and App activity  
appActivity-2
appActivity-3

Step→11

Once you enter the remote host and port number enter below capabilities to open calculator application from your android devic for android testing.

The images below illustrate how I started the Appium server using the Appium GUI and successfully opened the Calculator app in Appium Inspector with the specified capabilities and now it’s ready to inspect your app to prepare for automated testing efficiently. 

Step-11-1-Image app automation
Step-11-2-Image Android app automation

Conclusion:

Setting up Appium for testing on real Android devices can initially seem daunting due to the numerous steps involved and the technical nuances of configuring software and environment variables. However, by following this step-by-step guide, the process becomes manageable and straightforward.  

Investing the time and effort to configure Appium correctly pays off by significantly enhancing the efficiency and effectiveness of your mobile testing strategy. This setup not only improves the

Click here for more blogs of software testing and test automation.

How to execute Playwright-Js tests on BrowserStack

How to execute Playwright-Js tests on BrowserStack

        

Introduction:

At times, certain project specifications demand comprehensive testing of a web application across a diverse range of web browsers and their varying versions. Maintaining consistent functionality, visual appearance, and user engagement is essential.

To execute this type of cross-browser testing efficiently, there are two primary approaches:

  • One involves manual testing, where the website is examined across multiple browsers and devices. 
  • The other approach entails leveraging specialized tools and services that replicate distinct browser environments. 

Particularly, BrowserStack stands out as a tool that has garnered considerable attention in this field, thanks to its intuitive user interface.

Executing test cases on BrowserStack is crucial for QA teams to ensure the compatibility, functionality, and performance of websites and applications across a wide range of real browsers and devices. 

It helps identify bugs, responsive design issues, and user experience problems, while also supporting automated testing and real environment testing. 

BrowserStack eliminates the need for local testing infrastructure, reducing costs and enhancing overall testing efficiency.                                                   

So first let’s talk about the Basic Framework where we can automate test cases using the BDD approach to execute tests on a browser on the local machine. 

So for this instead of explaining it from scratch here again, You can explore my blog where I have explained How to create a BDD automation framework using Cucumber in JavaScript and Playwright.

This blog gives you step-by-step guidance on how to Create Feature files, Steps files, Page Files, and various other utilities to make the framework more reusable and robust. So here is the link to this blog: https://shorturl.at/bjuvU

You can also use the below link to access the BDD automation framework using Cucumber in JavaScript: https://github.com/spurqlabs/Playwright_JS_BDD_Framework

Pre-requisite:

To get started with BrowserStack implementation first store your BrowserStack username and access key in the .env file.
To get the username and access key to navigate to your BrowserStack account. Click on Access key dropdown from dashboard and you will be able to see your username and access key.

Here you will be able to see your account details. Copy your Username and Access Key and store it in a .env file as shown below. To execute tests on BrowserStack set the Browserstack variable to ‘true’.

Browserstack = true
BROWSERSTACK_USERNAME='browserstack_usename'
BROWSERSTACK_ACCESS_KEY='browserstack_accessKey'

Now to set BrowserStack configurations Create a file as “Browserstack.js”, as you can see I have created a “Browserstack.js file” in the Utility folder.

Playwright Framework


Here are the essential BrowserStack configurations to integrate into this file.

const cp = require('child_process')
const playwrightClientVersion = cp
    .execSync('npx playwright --version')
    .toString()
    .trim()
    .split(' ')[1]
function caps() {
    return {
        'browser': 'playwright-chromium',
        'os': 'Windows',
        'os_version': '10',
        'browserstack.username': process.env.BROWSERSTACK_USERNAME,
        'browserstack.accessKey': process.env.BROWSERSTACK_ACCESS_KEY,
        'client.playwrightVersion': playwrightClientVersion
    }
}
module.exports = { caps }
.execSync('npx playwright --version')
    .toString()
    .trim()
    .split(' ')[1]

.execSync:

The playwrightClientVersion variable is declared and assigned the output of the shell command executed using execSync from the child_process module.

.execSync('npx playwright --version’):

The command executed is npx playwright –version, which retrieves the version of the Playwright framework installed on the system. The output is converted to a string, trimmed to remove leading or trailing whitespace, and then split into an array based on spaces. The second element of the array (split(‘ ‘)[1]) represents the Playwright’s version.

caps():

This function is responsible for generating a configuration object used for browser testing with the BrowserStack platform and Playwright framework. It returns an object that contains configuration options for browser testing like browser, os, os_version, etc.

process.env.BROWSERSTACK_USERNAME, process.env.BROWSERSTACK_ACCESS_KEY:

These are the variables from the .env file. If you are not using a .env file you can directly pass the BrowserStack username and access key.

As we have all the configurations ready, we will set up a test environment to execute tests on BrowserStack. Use the file where you have your Before and After methods. In the playwright-Js Framework we have these methods stored in the ‘TestHooks.js file’ so will update that file as below.

const { Before, AfterAll } = require('@cucumber/cucumber')
const page = require('@playwright/test')
const path = require('path');
const { chromium } = require('playwright')
require('dotenv').config({
  path: path.join(__dirname, '../.env'),
});
Before(async (scenario) => {
  if (process.env.BrowserStack === 'true') {
    try {
      const capabilitiesBr = require('./BrowserStack').caps(scenario)
      global.browser = await chromium.connect({
        wsEndpoint: `wss://cdp.browserstack.com/playwright?caps=${encodeURIComponent(JSON.stringify(capabilitiesBr))}`,
      })
      viewport = {
        width: 1920,
        height: 900,
      }
    } catch (e) 
      console.error('Error connecting to BrowserStack', e)
    }
  } else {
    global.browser = await page.chromium.launch({ headless: false })
  }
  const context = await browser.newContext()
  global.page = await context.newPage()
})
AfterAll(async () => {
  await global.browser.close()
})

The above code Generates capabilities for BrowserStack using the caps() function from the ‘BrowserStack’ module. Construct the WebSocket endpoint URL for BrowserStack with the generated capabilities.

Now we have completed the BrowserStack implementation in our framework, now you can execute your tests on BrowserStack.

To execute tests on BrowserStack make sure you have “Browserstack = true” in the .env file.

Then you can execute your tests using the command ’npm run test’ on your terminal.

After running the test cases on BrowserStack, you’ll find the report below. Access comprehensive execution videos, and test logs for both successful and unsuccessful cases, along with execution duration.

Conclusion:

Integrating BrowserStack with Playwright JavaScript tests, gives access to a wide range of real browsers and devices, enabling comprehensive cross-browser and cross-platform testing. The scalability and cost-effectiveness of BrowserStack eliminate the need for maintaining an extensive device lab. Ultimately, this integration enhances test coverage, improves software quality, and ensures a seamless user experience across various browsers and platforms.

Read more blogs here

Role of Automated testing in Agile methodology

Role of Automated testing in Agile methodology

What are Agile methodologies?

Agile methodologies are nothing but an approach or practice that applies in Software development and Project management which makes the development process more efficient and helps to maintain the quality of software. It mainly focuses on collaboration, flexibility, and adaptability in the testing process. During development, the software testing practices adhere to the agile methodology.

There are several project management tools such as Kanban, Jira, Scrum, or Extreme Programming (XP).

The core process involved in Agile development:

Define Requirements:

The product owner or analyst along with the development team collaborates with each other and identifies, analyzes, and defines the requirements. User stories are created for specific sprints to define the requirements. And these user stories are collected in the product backlog or product board.

Sprint Planning:

Sprint planning is a process in which a product goal gets defined and a plan for the upcoming sprint is defined. Developers from the development team pick a set of requirements from the product board to work on the upcoming sprint. A Sprint meeting happens and the team identifies the scope of the upcoming sprint and breaks down the requirements into tasks.

Sprint Execution:

In Sprint Execution, the development team starts working on user stories in a time-bound iteration called a Sprint. Daily scrum call meetings are conducted to discuss progress, work, and any impediments during the sprint.

Continuously Integration:

Continuously Integration is a process, where developers make changes in code and those changes are also merged in a remote repository (GitHub) and tested frequently. It automates stages of the project pipeline such as – build, test, and deployment. It helps to team working within agile development.

Agile Testing:

Testing activity occurs in the early phase of the development process. In this phase, the tester collaborates with the developer and PO to understand the requirement and also starts testing the module, and defines the acceptance criteria. Testers start preparing test scenarios and test cases based on user stories. And they execute test cases and report bugs using bug-reporting tools such as Jira.

Incremental Delivery:

In the incremental Delivery phase, a small, developed part of the software is delivered to the customer at the end of each sprint. It helps to improve the quality of software by delivering it in small parts.

Sprint Review:

The Dev team, Pos, and QAs are involved in the Sprint Review meeting. In this phase, Sprint review takes place. Here development team presents work accomplished or gives a demo of whatever they have developed in that sprint. The incomplete issues, backlog adjustments, and Action items are discussed in this meeting.

Sprint Retrospective:

The agenda of this meeting is to examine how Sprint went as far as people, requirements, relationships, processes, and tools.         

Discussions Include:

  • What did we do well?
  • What should we have done better?
  • Identifies area for improvement
  • Suggestions
  • Actions

Let’s talk about Automated Testing:

Automated testing is an Agile practice that allows you to automate test cases through automation tools and execute the test cases to verify the functionality of software applications to meet customer expectations. It is a key aspect of agile development. Automated testing emphasizes manual testing efforts and also provides a way for continuous testing, early bug detection, and quick feedback.

Important aspects of Automated Testing:

  • Test Automation Framework: The team creates an automation framework using specific technology as per requirement and maintains it. It is a structured set of a rule and resources and tools which helps to create, execute, and automated the test cases. It allows us to reuse the code, in test data and also provides a way to generate test results or reports for execution.
  • Continuous Integration: The automation tool makes continuous integration easier when developers make changes in code and those changes are merged in a remote repository (GitHub) and tested frequently. Automated testing is an integral part of this process.
  • Regression Testing: Automated testing plays a vital role in regression testing. It makes sure that there should not be any unintended side effects occurring in the module when new changes have been made. Automation regression tests can be executed fast and repeatedly, giving quick feedback.
  • Continuous Delivery and Deployment: Automated testing allows us to run test suites to ensure that the changes made meet functional expectations and maintain the effectiveness and quality of the product. After completion of the automated testing phase, there is a Continuous Delivery process in which changes are automatically continuously deployed to the staging environment for testing. With this process code, the changes are continuously updated with the latest changes which makes faster delivery of the product in an efficient way.

Benefits of Automated Testing in Agile Methodologies:

  • Faster Feedback: Automated testing provides feedback quickly. It also helps in executing tests, generating results, and finding issues very quickly in the development cycle.
  • Increased Coverage: Automated testing allows you to create a wider range of test scenarios and test cases compared to manual tests.
  • Consistency-It helps to keep consistency in the execution of test cases, reducing human errors. Automated code itself needs to be tested to makes sure consistency and high quality.
  • Time and Cost Efficiency: Automated testing reduces human efforts and it is used in repetitive tasks, so it saves time and resources in the long run.

The working of CI/CD for automation testing in Agile:

CI/CD stands for Continuous Integration and Continuous Delivery as it is a pipeline that helps development teams to automate and makes it more efficient for building code, running tests, and also safely deploying code. The goal of the CI/CD method is to deploy code frequently and deliver working software to customers frequently and quickly.

Usually, Our source code is located on our local workstations. From there, we will commit our source code to the version control system, specifically using Git, which serves as our code management system, and is hosted on GitHub. Once the code is available in the code management system, the CI tool pulls that code automatically and builds under run unit test and then we call it Continuous integration.

During the CI process, we build and compile our source code and generate artifacts. Once these artifacts are generated, we need to deploy them on target env.

Target env may be changed based on the project necessities it may be a staging test, Dev or QA, preview, or production like various env we might have.

Now let’s take the artifacts we want to deploy on a staging environment.

Once it is deployed in the staging env we do the regression test and performance test. Once it successfully passes this test, it can be deployed to the production environment. During the deployment process, after the build, we move it into the staging environment, and if this transition to production can be achieved seamlessly without any manual intervention, we refer to it as Continuous Deployment.

In Continuous deployment, we can automatically deploy into the staging env and production environment.

Benefits of CI/CD:

  • Helps you to build better-quality software.
  • Automate the software release process for making delivery more efficient, rapid, and secure as well.
  • It helps you to automate repetitive tasks.
  • It reduces risks and makes the deployment process more predictable.
  • You can release software more frequently, which helps you to get fast feedback from your clients.
  • It gives a single view across all environments and applications.

What is Test Automation?

Test automation or automation testing is a process of automating test cases using automation tools and frameworks, managing test data, and asserting the automated result with requirements without any manual intervention. Automation testing plays an important role in achieving goals such as faster delivery, continuous integration, and frequent releases.

Benefits of Test Automation in Agile:

  • Faster Feedback: Automated tests can be executed quickly and also provide faster feedback on tests.
  • Improved Test Coverage: Automation tests allow running a large number of test cases across different environments hence it can cover different scenarios in the application.
  • Regression Testing Efficiency: Automation testing is mainly useful for running regression tests so it helps in repetitive testing after each code change.
  • Consistency and Accuracy: As automation testing is done without human intervention, it eliminates the possibility of human errors during test execution.

Benefits of Deployment Automation:

Deployment automation offers numerous benefits for software development, IT operations teams, and the entire organization. Automated deployment is a best practice in agile. Moreover, it allows developers to automate the deployment activities, development process, and testing activities. The following are the key benefits of deployment automation:

  • Faster and More Efficient Deployment: Automated deployment process is faster than manual deployment as it provides quick feedback. So that it reduces the time takes to release the software updates.
  • Consistency: Deployment automation ensures the consistency of the deployment across different environments (staging, dev, preview, production). So that it reduces the risk of configuration errors.
  • Reduce Human Errors: As Manual deployment involves humans which can lead to deployment errors, data loss, or other issues. So here, automation reduces such errors and increases the reliability of the deployment process.
  • Efficient Testing Environment: Automated deployment allows quick provisioning and teardown of the testing environment. This enables development and testing teams to work in isolation and concurrently, leading to faster testing cycles.
  • Cost Savings and Resource Optimization: Automated deployment reduces manual intervention which can lead to saving costs and resources.

Conclusion:

In conclusion, automated testing is an essential part of the dynamic landscape of the agile world. As we’ve explored this blog, it provides faster feedback, consistency, and accuracy, reducing risk and ensuring to delivery of high-quality software. Automation plays an important role in the form of CI/CD that helps you to build better-quality software.

Read more blogs here