Setting Up a Java Project in VS Code: A Step-by-Step Guide
Introduction
In this guide, I’ll walk you through setting up a modern Java project using Maven and TestNG in Visual Studio Code (VS Code). We’ll cover everything from project creation to running your first test, leveraging the VS Code Java Extension Pack for a seamless experience.
1. Installing the VS Code Java Extension Pack
To get started, install the Java Extension Pack by Microsoft in VS Code. This pack includes essential tools for Java development, such as language support, debugging, and Maven integration.
2. Creating a Maven Project
Open VS Code and launch the integrated terminal. Run the following command to generate a Maven project using the quickstart archetype:
mvn org.apache.maven.plugins:maven-archetype-plugin:3.1.2:generate \
-DarchetypeArtifactId="maven-archetype-quickstart" \
-DarchetypeGroupId="org.apache.maven.archetypes" \
-DarchetypeVersion="1.4" \
-DgroupId="com.example" \
-DartifactId="tutorial"
This creates a project structure with src/main/java and src/test/java folders, and a pom.xml for dependency management.
3. Setting Up TestNG
To use TestNG for testing, add the TestNG dependency to your pom.xml:
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.8.0</version>
<scope>test</scope>
</dependency>
4. Creating a SimpleTest Class
Inside src/test/java/com/example/, create a file named simpleTest.java:
package com.example;
import org.testng.annotations.Test;
public class simpleTest {
@Test
public void testMethod() {
System.out.println("TestNG is running!");
}
}
5. Configuring testng.xml
Create a testng.xml file in your project root to specify which tests to run:
<?xml version="1.0" encoding="UTF-8"?>
<suite name="Tutorial Suite">
<test name="SimpleTest">
<classes>
<class name="com.example.simpleTest"/>
</classes>
</test>
</suite>
6. Updating pom.xml for TestNG
Ensure your pom.xml includes the TestNG dependency and is set up for Java 21 (LTS):
<properties>
<maven.compiler.source>21</maven.compiler.source>
<maven.compiler.target>21</maven.compiler.target>
</properties>
7. Running Your Tests
Build and run your tests using Maven:
mvn test
You should see output from your simpleTest class, confirming TestNG is working.
Conclusion
With VS Code, Maven, and TestNG, you have a powerful setup for Java development. The Java Extension Pack streamlines your workflow, and TestNG makes testing easy. Happy coding!
Top comments (0)