The purpose of this blog is to provide a step-by-step guide on how to use Visual Studio Code for Java Selenium Automation as the Integrated Development Environment (IDE) for designing and running Selenium tests with Java. Visual Studio Code is a defacto IDE for JavaScript, however, it is rarely used for Java and Selenium automation as traditionally test automation engineers use either Eclipse or IntelliJ IDEA. Being one of the most widely used IDEs, software professionals prefer Visual Sstudio Code for its functionality.

  1. Cross-platform support: Visual Studio Code can run on Windows, macOS, and Linux
  2. IntelliSense: Visual Studio Code provides intelligent code completion and error detection, making it easier to write and debug code
  3. Built-in Git integration: Visual Studio Code provides built-in support for Git, allowing you to easily version control your projects
  4. Extensible with plugins: Visual Studio Code has a large community of developers who have created a variety of plugins to enhance the functionality of the IDE.
  5. Fast and lightweight: The design of Visual Studio Code focuses on being fast and lightweight, making it easy to use on lower-end hardware.
  6. Free and open-source: Visual Studio Code is free and open-source, making it accessible to everyone.
  7. Debugging and testing: Visual Studio Code has built-in support for debugging and testing, making it easier to identify and fix bugs in your code.
  8. Customization: You can customize Visual Studio Code with themes, keybindings, and settings, allowing you to tailor the IDE to your needs.

Here’s what you’ll need to get started with using Visual Studio Code for Java Selenium Automation:

  1. Java Development Kit (JDK): This is a software development kit that provides the necessary tools to create Java applications. You can download the JDK from the Oracle website (https://www.oracle.com/java/technologies/javase-downloads.html).
  2. Visual Studio Code: We can download from the Microsoft website (https://code.visualstudio.com/).

Once you’ve installed these components, you can create a new Java project in Visual Studio Code and add the Maven libraries to it.

Following the installation of these parts, you can use Visual Studio Code to build a new Java project and add the Maven libraries to your project.

Steps to setup in Visual Studio Code for Java Selenium Automation:

Assuming Visual Studio Code is installed, let’s start the recipe step by step to create a flow for execution.

Step 1:

You need to open Visual Studio Code and locate the Marketplace.

Step 1 Image.

Step 2:

Go to the search bar search for Java then Install the Extension pack for Java from the Marketplace.

Step 3:

Now, Navigate to the settings option in the lower left corner.

Step 3 Image

Step 4:

Select the command palette and look for the command create Java project. 

Step 4 Image

Step 5:

Probably, here we start how to add a maven repository into the project to run the Java-Selenium test using Visual Studio Code. After selecting Create Java Project, select the “Maven” option to help you create the project.

Step 6:

After that, it will navigate to the browse folder and choose a specific folder to create your Java project. Please select a folder and open it in Visual Studio Code.

Step 7:

The screen below will appear; enter your project name and press “Enter” to open that project in Visual Sstudio Code. 

Step 8:

Once you open the project, you will see the default folder structure displayed. To ensure code reusability, we create the following framework in Visual Studio Code.

  • Default Structure
  • Hybrid Framework folder structure

Hybrid Driven Framework is a combination of both the Data-Driven and Keyword-Driven frameworks. Here, we externalize the keywords, as well as the test data. Furthermore, Keywords are maintained in a separate Java class file and test data can be maintained either in a properties file/excel file/can use the data provider of a TestNG framework.

Step 9:

So, for adding Maven dependencies and how to download them

Maven is a tool for managing or building projects. When various test engineers incorporate their files into the same framework, they use it to check for compilation problems amongst framework components. Consequently, every time we make a change to the framework, we update the build status and continuously maintain the monitor, framework components, or build. As a result, there are no compilation errors in the framework, it will output a “build success” message; otherwise, it will output a “build failure” message.

Once you select Maven Project, it will create a Maven project with a pom.xml file. In the pom.xml file, you need to add the selenium dependency from the website https://mvnrepository.com/ and add it into dependency.

This dependency has been added to provide the libraries required to run the Selenium project. In a normal Selenium project, we need to download standalone libraries and then add them to external libraries, whereas here, once you add this Maven dependency, it will automatically download all libraries required for the Selenium project.

In a Maven project, you can use the Apache POI library by adding its dependency to your project’s pom.xml file. This will automatically download and include the library in your project’s classpath. Once you have added the dependency, you can start using the Apache POI APIs in your Java code to read, write, and manipulate Microsoft Office documents.

In a Maven project, you can add the Extent Reports dependency to your project’s pom.xml file to use its reporting functionality. Once you have added the dependency, you can start using the Extent Reports APIs in your Java code to create and generate detailed reports for your automation test results.

In a Maven project, you can add the TestNG dependency to your project’s pom.xml file to use its testing functionality. Once you have added the dependency, you can start using the TestNG annotations in your Java code to define your tests, test suites, and test configurations.

In a Maven project, you can add the Log4j dependency to your project’s pom.xml file to use its logging functionality. Once you have added the dependency, you can start using the Log4j APIs in your Java code to log messages to various output targets. You can configure Log4j using a configuration file such as log4j2.xml or log4j2.properties, which specifies the logging level, output target, and other logging settings.

Here, you need to run Java-selenium tests by using the pom.xml file, according to your demand and test requirements, Therefore, you can add more maven repositories.

1. Test/Java/example:

This folder contains the test source code packages and classes. Here, this contains all the data related to test cases, including page objects, base classes, and the test case class, which helps run the whole TestNG framework. However, this contains all the data related to test cases, including page objects, base classes, and the test cases class, which help run the whole TestNG framework.

Code Explanation in Demo example:

Login Page:

  • The base class in the main class will take care of browser setup, loading configuration files, and other reusable methods like screenshots, handling sync issues, and many more.
  • Using Base, we can avoid code duplication.
  • Reuse code as much as we can.
package com.example.Pages;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;

public class LoginPage {
    WebDriver driver;
    public LoginPage(WebDriver driver){
        this.driver = driver;
        PageFactory.initElements(driver, this);
    }

    @FindBy(id="email")
    WebElement usernameBox;

    @FindBy(id="passwd")
    WebElement passwordBox;

    @FindBy(name="SubmitLogin")
    WebElement SignInBtn;

    public void enterUsername(String uname){
        usernameBox.sendKeys(uname);
    }

    public void enterPassword(String upwd){
        passwordBox.sendKeys(upwd);
    }

    public void submitButton(){
        SignInBtn.click();
    }
}

Base Class:

  • @BeforeClass: The annotated method will be run before the first test method in the current class is invoked.
  • @AfterClass: The annotated method will be run after all the test methods in the current class have been run.
package com.example.TestCases;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import com.example.Utilities.ReadConfig;
public class BaseClass {
    ReadConfig read = new ReadConfig();
    public String googlebaseurl = read.getGoogleBaseURL();
    public String loginbaseurl = read.getLoginBaseURL();
    public String uname = read.getUsername();
    public String upwd = read.getPassword();
    public String SuccessURL = read.getSuccessURL();
    public WebDriver driver; 
    public Logger logger;
    @BeforeClass
    public void SetUp(){
        System.setProperty("webdriver.chrome.driver", "Drivers/chromedriver.exe");
        // WebDriverManager.chromedriver().setup();
        driver = new ChromeDriver();
        driver.manage().window().maximize();

        logger = Logger.getLogger("googledemo");
        PropertyConfigurator.configure("log4j.properties");
    }

    @AfterClass
    public void tearDown(){
        driver.quit();
    }
}

Test Class:

According to the below code, This class will help to run TestNG test cases and will give results. You can add third-party tools for generating reports as well such as extent reports, and Allure reports.

package com.example.TestCases;

import java.io.File;
import java.io.IOException;

import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.testng.Assert;
import org.testng.annotations.Test;

import com.example.Pages.LoginPage;
import com.google.common.io.Files;

public class TC_LoginTest extends BaseClass{
    @Test
    public void LoginToWebsite(){
        LoginPage Lp = new LoginPage(driver);
        driver.get(loginbaseurl);
        Lp.enterUsername(uname);
        Lp.enterPassword(upwd);
        Lp.submitButton();
        if (driver.getCurrentUrl().equals(SuccessURL)) {
            Assert.assertTrue(true);
        } else {
            Assert.assertTrue(false);
        }
        File screen = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
        try {
            Files.copy(screen, new File("Screenshots/login.jpg"));
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }
}

2. Drivers:

Basically, this folder is used to store browsers that will be required to run test cases on that specific browser. Whether it is Chrome, Edge, or Opera. Further includes driver information, where the Chrome Driver, Firefox, or Edge—whichever you’re comfortable with. Even you can use maven dependency for instantiating Webdriver. The WebDriverManager is a library that allows you to automate the management of WebDriver binaries. There are such as Chrome driver, gecko driver, etc. in your Java project.

3. Configuration:

The Above image implies that properties are used to externalize configurable data. Because if you put that data in your code (test script), you would need to build the code each time you wanted to modify the property’s value. As a result, the fundamental advantage of properties is that they may be modified at any time. And exist independently of your source code. Thus, a pair of strings is used to store each parameter, with one string serving as the key and the other as the value.

You can see the folder structure, where the configuration folder contains a config file that includes all the common information required to run a test.

4. Utilities:

Once we have the config file loaded, we need to read the properties of the config file. The Properties object gives us the .getPropertymethod that takes the key of the property as a parameter and returns it. Basically, the value of the matched key from the .properties file. Therefore, this includes a class that assists in reading all of the data from the config.properties file. 

5. Screenshots:

A screenshot in Selenium WebDriver is there we can use for bug analysis. Selenium WebDriver can automatically take screenshots during the execution. But if users need to capture a screenshot on their own, they need to use the Take Screenshot method. So, which notifies the WebDriver to take the screenshot and store it in Selenium. As a result, it includes screenshots that we took at the time of running the test.

6. log4j.properties:

The above image log4j.properties is a configuration file that we can use with the Apache Log4j logging framework. As a result, which is a popular logging library for Java applications. Users utilize this file to configure the logging behavior of the application, including specifying the output destination for log messages. The format of log messages, and the logging levels for different categories of log messages. The log4j.properties file contains key-value pairs that define the various logging settings for the application.

Step 10:

Basically, here is how we organize the hybrid framework. We need to add a few folders to make it easier for testers to run code without encountering them.

Initially, you will not find any errors until you save your code in Visual Studio Code through ctrl+s. You can hover over that error and you will find a solution for that. If you need to install any package, Thus it will also be visible to you.

Run Test:

  1. Navigate to the Project Directory:- Open a command prompt or terminal window. And navigate to the directory where your Maven project is located. This should be the directory that contains the “pom.xml” file, which is the Maven project configuration file.
  2. Run Maven Test Command:- Once you are in the project directory, you can run the following command to execute the Maven tests: “mvn test”
  3. This command will instruct Maven to run the tests defined in your Maven project. Maven will automatically compile the necessary source code and download dependencies. And execute the tests using a testing framework such as JUnit, TestNG, or any other testing framework that you have configured in your project’s dependencies.
  4. View Test Results:- After the tests have been executed. The Maven will display the test results in the command prompt or terminal window. You can view the test results to see which tests have passed, failed, or skipped.

Video:

Accordingly, the below tutorial will guide you

Conclusion:

Since Visual Studio Code for Java Selenium m Automation is a well-known IDE among software professionals. Here, I can think of no better method to run Java-Selenium automation through VSCode.

However, It offers the best Java extension for using Visual Studio Code for Java Selenium Automation. Basically, we make run test cases more appropriate and adaptable.

Read more blogs here
5