This tutorial will focus on how to setup Selenium to run tests in Java using Visual Studio Code IDE.
Setup Visual Studio Code For Java
- Install Java Extension Pack for Visual Studio Code
- create new standalone Java project
- click “Create Java Project”
- select standalone (no build tools)
- name the project
- a new Visual Studio Code window will be created with the new project; the new project will have a lib and src folder, “Hello World” java file and a Readme
- click “Create Java Project”
Setup Selenium WebDriver
- Download the latest stable Selenium Web Driver for Java – this will be a zip file: (e.g. selenium-java-3.141.59.zip)
- unzip the file and there will be multiple jar files – it’s important to add ALL the jar files to the project’s dependencies
- we need client-combined-3.141.59.jar for compiling our Selenium code
- we need the rest of the jars for running Selenium
- add all six jars to the project by clicking the “+” next to Referenced Libraries
Setting up ChromeDriver
- Download ChromeDriver. The ChromeDriver major version has to match your Chrome version. In my case, my Chrome version is 89.0.4389.90 so I downloaded ChromeDriver version 89.0.4389.23
- unzip ChromeDriver zip and move it to a central folder that will be referenced by multiple projects (e.g. ~/dev/selenium/bin/ on a Mac)
- configure ChromeDriver to be discoverable by WebDriver in one of two ways:
- option1 – add ChromeDriver binary to the PATH variable
- export PATH=$PATH:~/dev/selenium/bin/ (Mac)
- test that it’s set correctly by executing “chromedriver” from another directory – you should see ChromeDriver start and you can press CTRL-C to stop it; this will allow multiple projects to use the same ChromeDriver binary
- option 2 – add the path to ChromeDriver in your test code:
-
System.setProperty(“webdriver.chrome.driver”, “~/dev/selenium/bin/chromedriver”);
-
- option1 – add ChromeDriver binary to the PATH variable
Run Selenium
Now that all the setup is in place, we’re ready to develop and run Selenium code.
We’ll first develop a simple Selenium script that opens a Chrome browser and navigates to google.com and then quits.
1
2
3
4
5
6
7
8
9
10
11 import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class App {
public static void main(String[] args) throws Exception {
System.out.println("Hello, World!");
WebDriver driver = new ChromeDriver();
driver.get("https://www.google.com");
driver.quit();
}
}
There are a few way to run a Java project in Visual Studio Code:
Option 1 – run from Java Projects view. When you hover over your project name a play button will appear that will run the code.
Option 2 – Directly from your code’s main method.