Desktop Automation Made Easy: A Winium, Java, and BDD Guide

Desktop Automation Made Easy: A Winium, Java, and BDD Guide

Desktop application test automation can be a tedious task as it’s hard to locate the elements and interact with those elements. There are plenty of tools available for automating desktop applications. Winium is one of those tools which is a selenium-based tool. So for those who don’t have an idea about Selenium, Selenium is a web application test automation tool that supports almost all programming languages. (Wish to learn more about selenium? Check out the link here) If you are familiar with the Selenium tool then it’s going to be easy for you to understand the workings of the Winium tool as most of the methods are common and if you are not familiar with Selenium no worries, I have got you covered. 

Coming back to our topic, In this blog we will see how we can create a robust test automation framework for automating desktop applications using Winium a desktop application automation tool, Java as a programming language, Maven, as a dependency management tool, Cucumber as a BDD (Behavior Driven Development) tool. We are going to build a test automation framework from scratch. Even if you don’t have any idea on how to create a framework no worries. 

Before we start building the framework let’s complete the environment set-up. So for this, we will have to install some tools. Below I am sharing the URLs of the tools we are using just in case if you want to know more about these tools then you can visit these official web pages. 

  • As we are using Java programming it is a must to have JDK installed on the system. 
  • You can download the JDK (Make sure the version is greater than 8) For instance I have the Java 11.0.16.1 version set up on my system. 
  • Use this link to download the Java SE Development Kit – https://www.oracle.com/in/java/technologies/javase/jdk11-archive-downloads.html
  • Once the download is completed the next step is setting up the path in the environment variables. Check the below screenshots to set up the path in your system environment variables
  • Once you are done with the above steps then you should see the below information in the command prompt.
  • Once you are done with Java Installation and set up the next step is to do the installation and set up the maven. 
  • To download the maven you can visit this official web page – https://maven.apache.org/download.cgi
  • Again after installation, we have to set up the environment variable path for our system. 
  • See the below screenshots for your reference.
  • We need an inspector to inspect the desktop application elements. We use different approaches and tools to inspect and locate the web page elements. 
  • Here we will use the Inspect.exe tool to inspect and locate the desktop application elements. 
  • Use this link to download and install the tool – https://github.com/blackrosezy/gui-inspect-tool/blob/master/Inspect.exe
  • Not only that there are other desktop application element inspection tools. 
  • Once you are done with the above steps then we can start building the automation framework. 

The BDD (Behavior-Driven-Development) is a software development approach that focuses on collaboration among stakeholders, including developers, QA engineers, and business analysts. The reason behind this is that in the BDD approach, we use natural language specifications to describe software behaviour from the end user’s perspective. I believe this helps in creating a shared understanding of requirements and promotes effective communication throughout the development lifecycle. Let’s see this in detail, 

  • Feature files are the main component of the BDD cucumber framework we can even say they are the heart of this cucumber framework. 
  • These files are written using gherkin language which describes the high-level functionalities of the application. 
  • Cucumber is a widely used BDD tool as it allows us to write test cases (scenarios) in plain tests using the Gherkin syntax. 
  • This is because Gherkin uses keywords like, Given, When, And, and Then to structure scenarios, making it easy to read and understand by both technical and non-technical stakeholders. 
  • Here is the one scenario that I have created for this framework. 
  • Yes, that’s correct. Step definition files contain code that maps the steps in the feature file to automation code. 
  • These files are written using the programming language used in the automation framework, in this case, Java.
  • The step definitions are responsible for interacting with the elements of the application and performing actions on them such as clicking, entering text, etc. 
  • They also contain assertions to check if the expected behaviour is observed in the application.
  • In Cucumber, hooks are methods annotated with @Before and @After that run before and after each scenario. 
  • To ensure consistency between test environments, these hooks are used for setting up and taking down tests. 
  • The application can be initialized before and cleaned up after each scenario using hooks, for example.

The Page Object Model (POM) is a design pattern that assists in building automation frameworks that are scalable and maintainable. In POM, we create individual page classes for each application page or component, which encapsulates the interactions and elements associated with that particular page. This approach improves code readability, reduces code duplication, and enhances test maintenance.

In a test automation framework, utility files provide reusable functionalities, configurations, and helper methods to streamline the development, execution, and maintenance of test scripts. As a result, they enhance the efficiency, scalability, and maintainability of the automation framework. Listed below are a few common utility files, along with their functions:

  • This utility file handles the launch and termination processes of the desktop application, as well as the Winium driver 
  • When we use Winium as a desktop application automation tool we have to start the server. (Winium Driver). 
  • Either we can do this manually before starting the execution of the test case or we can do this through automation as well. 
  • In the below utility file there are methods created for launching the desktop application and Winium driver (server). 
  • This common util file reads or retrieves the values and files present in a particular folder (referenced here as the resource folder).
  • This file can further serve as a basis for developing additional common methods usable throughout the framework.
  • The TestRunner class executes Cucumber tests with specified configuration settings, including the location of feature files, step definitions package, inclusion tags, and report generation plugins.
  • The seamless integration of Cucumber tests into TestNG makes testing and reporting easy.

Once we have defined the test scenarios, we will use Maven commands to execute them. Maven is a robust tool that manages project dependencies and automates the build process. With Maven, we can run automated tests with ease and ensure a smooth and efficient testing process.

  • In the project’s Maven Project Object Model (POM) file, we define the necessary configurations for test execution. 
  • This includes specifying the test runner class, defining the location of feature files and step definitions, setting up plugins for generating test reports, and configuring any additional dependencies required for testing.

Once you configure the automated tests in the Maven POM file, you can run them using Maven commands from the terminal or command prompt. Common Maven commands used for test execution include:

  • mvn test – This command runs all the tests from the project.
  • mvn clean test – This command first cleans the project (removes the target directory) and then runs the tests.
  • mvn test “-Dcucumber.filter.tags=@tagName” – This command runs tests with specific Cucumber tags.

Cucumber provides built-in support for generating comprehensive test reports. By configuring plugins in our automation framework, we can generate detailed reports that showcase the test results, including passed, failed, and pending scenarios. These reports offer valuable insights into the test execution, helping us identify issues, track progress, and make data-driven decisions for test improvements.

Automating desktop applications with Winium, Java, and Behavior-Driven Development (BDD) using Cucumber is a strategic approach that offers numerous benefits to software development and testing teams. By combining these technologies and methodologies, we create a robust automation framework that enhances software quality, reduces manual efforts, and promotes collaboration across teams.

In conclusion, automating desktop applications with Winium, Java, and BDD using Cucumber empowers teams to deliver high-quality software efficiently. By leveraging the strengths of each technology and following best practices such as the Page Object Model and Maven integration, we create a solid foundation for successful test automation that aligns with business goals and enhances overall product quality.

You can access the complete source code of the created automation framework for desktop applications using Winium, Java, and BDD with Cucumber on GitHub at https://github.com/spurqlabs/Desktop-App-Winium-Java-Cucumber The framework includes feature files, step definitions, page classes following the Page Object Model, Maven dependencies, and configuration files for generating Cucumber reports. Feel free to explore, fork, and contribute to enhance the framework further.

Read more blog here

API Test Automation using Playwright and Java

API Test Automation using Playwright and Java

 Most of us are familiar with API testing tools like Postman, SoapUI, etc, and API automation libraries like RestAssured and Karate to automate API test cases. A recent entrant in this category is Playwright. The playwright is an Automation Tool provided by Microsoft. It provides cross-browser testing using which we can perform testing on multiple browsers like Chromium, Webkit, Firefox, etc. playwright supports cross-language testing (Java, Node.js, Python, .NET, etc.). However, very few of us know that it can actually do an API Test automation of methods GET, PUT, POST, and DELETE. Let’s see how it can be done.

Can we perform API testing using Playwright?

The playwright provides inbuilt support for API testing that’s why we don’t need any external libraries to handle API. The playwright doesn’t use any browser to call API. It sends requests using Node.js which provides faster execution.

In this tutorial, we will explore basic API methods with the help of Playwright- java. Below are the Four methods.

  1. GET
  2. POST
  3. PUT
  4. DELETE

Pre-requisite:

To get started with API automation with playwright-java first we need playwright to be installed in your system, to do this we can simply add the following dependency in the pom.xml file.

Along with the playwright, we have to add Testing and JSON dependencies.

<dependency>
  <groupId>com.microsoft.playwright</groupId>
  <artifactId>playwright</artifactId>
  <version>1.23.0</version>
</dependency>

<dependency>
   <groupId>org.testng</groupId>
   <artifactId>testng</artifactId>
   <version>7.1.0</version>
   <scope>test</scope>
</dependency>

<dependency>
   <groupId>com.googlecode.json-simple</groupId>
   <artifactId>json-simple</artifactId>
   <version>1.1.1</version>
</dependency>

Now let’s see how we can start API automation testing with Playwright-java.

1. GET:

By providing an API endpoint we can read data using a GET request. We must pass a few parameters to get the required data from the API.

We can verify the request by asserting the Response Code. The response code for a successful GET Request is 200. You can also assert a text inside the JSON body response.          

For Example, I am using postman here to send a GET request to ”  ‘/api/users/4’ endpoint of a sample API URL ‘https://reqres.in’

The below code shows the implementation of the GET method through Playwright.

@Test
public void get() throws IOException, ParseException {
   Playwright playwright = Playwright.create();
   String BaseURL="https://reqres.in";
   Map<String, String> headers = new HashMap<>();
   headers.put("content-type", "application/json");
   APIRequestContext apiRequestContext= playwright.request().newContext(new APIRequest.NewContextOptions()
           .setBaseURL(BaseURL).setExtraHTTPHeaders(headers));
   APIResponse response = apiRequestContext.get("/api/users/4");
   int responseCode=response.status();
   Assert.assertEquals(responseCode,200);

   String responseText= response.text();
   JSONParser j= new JSONParser();
   JSONObject json = (JSONObject) j.parse(responseText);

   String responseData= json.get("data").toString();
   JSONObject jsonData = (JSONObject) j.parse(responseData);
   Assert.assertEquals(jsonData.get("email"),"eve.holt@reqres.in");
   Assert.assertEquals(jsonData.get("first_name"), "Eve");
   Assert.assertEquals(jsonData.get("last_name"), "Holt");
   Assert.assertEquals(jsonData.get("avatar"), "https://reqres.in/img/faces/4-image.jpg");
   apiRequestContext.dispose();
   playwright.close();
}

To verify the response data we are parsing the response to JSON Object so that we can verify specific key-value pairs.

2. POST:

POST method is used to add a new record via API where we have to pass data as payload ex. first name, last name, etc. The response code for a successful POST Request is 201.

For example, I am sending a POST request to  ‘/api/users/’ endpoint with base URL ‘https://reqres.in‘ and the body as given below in the screenshot:

To pass the data payloads to the POST/PUT method, first, we have to create a POJO class which will help to create methods to get and set payloads.
below we have created a POJO class employee which will help to get and set data to both POST and PUT calls.

public class Employee {
// private variables or data members of pojo class
private String email;
private String first_name;
private String last_name;
private String avatar;

public String getEmail() {
   return email;
}
public void setEmail(String email) {
   this.email = email;
}
public String getFirstName() {
   return first_name;
}
public void setFirstName(String firstName) {
   this.first_name = firstName;
}
public String getLastName() {
   return last_name;
}
public void setLastName(String lastName) {
   this.last_name = lastName;
}
public String getAvatar() {
   return avatar;
}
public void setAvatar(String avatar) {
   this.avatar = avatar;
}
}

The below code will help you with the POST method through Playwright.

@Test
public void post() throws ParseException {
   employee employee = new employee();
   employee.setEmail("john@reqres.in");
   employee.setFirstName("john");
   employee.setLastName("Holt");
   employee.setAvatar("https://reqres.in/img/faces/4-image.jpg");

   Playwright playwright = Playwright.create();
   String BaseURL = "https://reqres.in";
   Map<String, String> headers = new HashMap<>();
   headers.put("content-type", "application/json");
   APIRequestContext apiRequestContext = playwright.request().newContext(new APIRequest.NewContextOptions()
           .setBaseURL(BaseURL).setExtraHTTPHeaders(headers));
   APIResponse response = apiRequestContext.post("/api/users/", RequestOptions.create().setData(employee));

   Assert.assertEquals(response.status(),201);
   String responseText= response.text();
   JSONParser j= new JSONParser();
   JSONObject json = (JSONObject) j.parse(responseText);
   Assert.assertEquals(json.get("email"), employee.getEmail());
   Assert.assertEquals(json.get("first_name"), employee.getFirstName());
   Assert.assertEquals(json.get("last_name"), employee.getLastName());
   Assert.assertEquals(json.get("avatar"), employee.getAvatar());
   apiRequestContext.dispose();
   playwright.close();
}

3. PUT:

PUT Request is used to update the existing records via the API. we have to pass the data we want to update as a payload ex. first name, last name, etc. The response code for a successful PUT Request is 200.

For example, I am sending a POST request to ‘/api/users/55’ endpoint with the base URL ‘https://reqres.in’ and the body as given below in the screenshot:

The below example shows the implementation of the PUT method. We need to use the above POJO class to pass the data as a payload to the PUT call.

 @Test
public void put() throws ParseException {
   employee employee = new employee();
   employee.setEmail("john@reqres.in");
   employee.setFirstName("Harry");
   employee.setLastName("Eve");
   employee.setAvatar("https://reqres.in/img/faces/4-image.jpg");

   Playwright playwright = Playwright.create();
   String BaseURL = "https://reqres.in";
   Map<String, String> headers = new HashMap<>();
   headers.put("content-type", "application/json");
   APIRequestContext apiRequestContext = playwright.request().newContext(new APIRequest.NewContextOptions()
           .setBaseURL(BaseURL).setExtraHTTPHeaders(headers));
   APIResponse response = apiRequestContext.put("/api/users/55", RequestOptions.create().setData(employee));

   Assert.assertEquals(response.status(),200);
   String responseText= response.text();
   JSONParser j= new JSONParser();
   JSONObject json = (JSONObject) j.parse(responseText);
   Assert.assertEquals(json.get("email"), employee.getEmail());
   Assert.assertEquals(json.get("first_name"), employee.getFirstName());
   Assert.assertEquals(json.get("last_name"), employee.getLastName());
   Assert.assertEquals(json.get("avatar"), employee.getAvatar());
}

4 DELETE:

We can delete existing records using the API by using DELETE Request. Ideally, you must have added a record before you delete it. Hence you would need to append an ID to the DELETE URL. To delete the record using API first we need to pass the record URI (Universal Resource Identifier). The response code for a successful DELETE Request is 200.

For example, I am sending a POST request to ‘https://retoolapi.dev’ endpoint with base URL ‘/3njSPM/calc/43’ and the body as given below in the screenshot:

Following is the code for the DELETE method in Playwright

@Test
public void delete()  {
   Playwright playwright = Playwright.create();
   String BaseURL = "https://retoolapi.dev";
   APIRequestContext apiRequestContext = playwright.request().newContext(new APIRequest.NewContextOptions()
           .setBaseURL(BaseURL));
   APIResponse response = apiRequestContext.delete("/3njSPM/calc/40");
   int responseCode = response.status();
   Assert.assertEquals(responseCode, 200);
   Assert.assertEquals(response.statusText(), "OK");
   apiRequestContext.dispose();
   playwright.close();

 

After performing a DELETE call we can perform a GET call on the same endpoint to verify data is actually deleted. For this GET call, we will get response code 204 as the content is not found.

For Reference: https://playwright.dev/java/docs/api-testing

Conclusion:-

GET, PUT, POST, and DELETE are the basic CRUD API methods used in any Web application. With the help of the inbuilt functionalities of Playwright, API Automation Testing became much easier and faster.

Read more blogs here