You build a JUnit test in Visual Studio Code by installing a Java Development Kit and the Extension Pack for Java, adding JUnit 5 to the project, writing a test class under src/test/java, and then running or debugging it through the Testing sidebar or CodeLens links above each method. The one condition that trips most people up is project type: a plain folder needs a build tool such as Maven or Gradle to manage the JUnit dependency, while an existing Spring Boot or Maven project already has the structure waiting for you.
VS Code is a capable Java environment once the extensions are in place, but it is not an IDE that hands you a working test project out of the box. This guide covers the prerequisites, two supported project routes, the naming and package conventions that let the test runner discover your code, concrete test-writing patterns, and the failures you will actually hit. Version details reflect stable, long-standing behavior as of late 2026; check your extension's release notes if the UI looks different.
What you need installed before writing the first test
Four pieces need to be in place, and skipping any of them produces confusing partial behavior rather than a clean error.
A Java Development Kit. JUnit 5 requires Java 8 as a minimum, but current builds of the VS Code Java tooling target Java 11 and newer, and Java 17 or 21 is the reasonable default for new work in 2026. Install a distribution such as Eclipse Temurin or Microsoft Build of OpenJDK and confirm it from a terminal with java -version and javac -version. Both commands should report the same major version; a mismatch between the runtime and compiler is a recurring source of build errors.
Visual Studio Code with the Extension Pack for Java, published by Microsoft. This bundle includes the Language Support for Java server, the Debugger for Java, the Test Runner for Java, Maven for Java, and the project manager. Install it as a single item from the Extensions view rather than assembling the parts individually.
A build tool, meaning Maven or Gradle, for any project that is not already scaffolded. The test runner can detect JUnit when a build file declares it; a bare folder of .java files has no dependency resolution.
Optionally, Spring Boot Extension Pack if you are working in a Spring application, though the base Java pack plus Maven covers testing on its own.
The extension status is easy to verify: open the Extensions view, filter to installed, and check that "Extension Pack for Java" shows no error badge. In the bottom status bar you should see a Java language level indicator, and the Testing view should appear in the activity bar even before any tests exist.
Choose a project route before writing anything
You have three realistic starting points, and the right one depends on what already exists. A Maven project is the most predictable for testing. A Gradle project works identically through the test runner but with different file syntax. A Spring Boot project generated from the Spring Initializr arrives with Maven or Gradle and a test dependency already declared, making it the fastest path if you are building an application anyway.
A plain non-build folder is the trap. The Java extension can compile and debug single files, but the Test Runner for Java looks for JUnit on the project classpath, which for a simple folder means searching for JARs in a lib/ directory. That arrangement is fragile and not worth configuring by hand for something Maven solves in one file. Unless you are teaching yourself classpath mechanics, use a build tool.
If you have no project at all, the cleanest route is outside VS Code: generate a Maven project from the Spring Initializr with the web dependency omitted and the test dependency included, unzip it, and open the folder in VS Code. Let the extension import finish before touching anything; the progress indicator in the status bar will settle.
Setting up JUnit 5 in a Maven project
The Maven route centers on pom.xml. JUnit 5 is distributed as several artifacts, and the junit-jupiter aggregate artifact pulls the API, engine, and params modules together at a matching version. Add it with test scope so it never leaks into your production artifact:
The test element matters. It confines the dependency to the test classpath, and the test runner relies on that separation. If you paste the dependency without scope, JUnit ends up packaged in your application.
Maven expects sources in src/main/java and tests in src/test/java, mirroring package structure. A class com.example.calc.Calculator in main is tested by com.example.calc.CalculatorTest in src/test/java/com/example/calc/CalculatorTest.java. Keep the package declaration identical. A test in a different package can still run, but it cannot reach package-private methods, which is often exactly what you want to test.
For a version upgrade, note that the JUnit 5 line has continued to ship 5.x releases; the Jupiter API has stayed source-compatible for the annotations and assertions used here across the 5.x series. Pin the version in the POM rather than relying on inheritance from a parent POM unless the parent manages it deliberately.
Success check: after saving pom.xml, the Java Projects view should list the JUnit dependency under the project's test classpath, and a green Testing icon should appear. If you open the Testing view and see your project name with a "no tests found" message, the setup is working; you just have no test classes yet.
Creating a Gradle-based test project instead
Gradle handles the same dependency with testImplementation:
The useJUnitPlatform() line is not optional. Gradle's default test task historically used the JUnit 4 runner, and without telling it to use the JUnit Platform, your Jupiter tests are silently skipped. This is one of the most common "my tests don't run" causes in Gradle projects, and the symptom is a passing build with zero tests executed rather than an error.
Gradle uses the same src/test/java convention by default. The test runtime launcher dependency became effectively required in Gradle 9 and later for correct test discovery, so include it even though older tutorials omit it.
Refresh the project after editing build files by using the Gradle view's refresh action, or run ./gradlew test once from the integrated terminal to confirm the toolchain works outside the extension as well. That terminal run is a useful diagnostic because it separates build-tool problems from extension problems.
Writing a test class that the runner can actually find
Discovery depends on a small set of rules. The class must be a top-level or static nested class, not an inner class, and the simplest reliable approach is a package-private public class with a name ending in Test, Tests, or TestCase. The runner scans for those patterns by default. A class named CalculatorChecks will be ignored even if it contains perfect JUnit methods.
Here is a working test for a small Calculator class with an add method:
A few conventions in that example carry real weight. Test methods are usually package-private and need no public modifier under JUnit 5; the @Test annotation is what counts, and the method name reads as a sentence describing the expected behavior. The @BeforeEach method runs before every test, so each test gets a fresh instance and no shared state leaks between them. The static imports of assertEquals and assertThrows come from org.junit.jupiter.api.Assertions; forgetting them, or importing the JUnit 4 org.junit.Assert, produces compile errors because JUnit 4's argument order is expected first and JUnit 5's is expected first too but the class differs. Confirm you are importing from jupiter.
Running, debugging, and reading the results
Three entry points exist and they all invoke the same runner. CodeLens links appear above each @Test method ("Run Test", "Debug Test") and above the class declaration to run the whole class. The Testing view in the activity bar shows a tree of packages, classes, and methods with play and bug icons, plus a "Run All Tests" button and a refresh icon. The command palette offers "Java: Run Tests" and "Java: Debug Tests" for whatever file is active.
Running gives you pass and fail badges inline with the source, a results tree in the Testing view, and, for failures, a diff of expected versus actual values plus a stack trace that points at the failing assertion line. Debugging is genuinely useful: set a breakpoint in the test or in the production code, choose Debug Test, and step through with the standard debug toolbar. The debugger honors breakpoints in main code, which makes a failing integration of two methods easier to diagnose than reading a stack trace.
A subtlety about state: JUnit creates a new instance of the test class for each test method by default. Field initializers and @BeforeEach therefore run per test, and you should not assume ordering between test methods. If tests pass individually but fail together, look for static mutable state or shared external resources such as a database or a temp file that one test leaves dirty.
Success check for the whole workflow: clicking Run Test above addsTwoPositiveNumbers shows a green check, the Testing view lists one passed test, and the terminal output contains a summary line reporting tests run with zero failures. If the CodeLens links do not appear at all, the class is not being recognized as a test: check the file lives under src/test/java, the package matches the directory, and the dependency resolved.
For larger suites, JUnit 5's parameterized tests let one method cover many inputs:
This requires the junit-jupiter-params module, which the aggregate artifact includes. Running it reports each row as a separate invocation with its own index, so a single failing input is identifiable without splitting the method.
Fixing the failures you will actually hit
Tests are not discovered. Usually this is a naming problem: the class name lacks the Test suffix, or the file sits in src/main/java rather than src/test/java. In Gradle, it is often the missing useJUnitPlatform(). In rare cases the Java server needs a restart; use "Java: Clean Java Language Server Workspace" from the command palette, which forces a re-import.
Compile errors on @Test. The import is wrong or the dependency did not resolve. Check for org.junit.Test (JUnit 4) versus org.junit.jupiter.api.Test (JUnit 5). If the POM edit did not trigger a reload, run "Java: Reload Projects" or execute mvn test in the terminal to force resolution.
Runtime error: no tests found for the launcher. This typically means the JUnit Platform launcher is absent from the test runtime classpath. On Gradle, add testRuntimeOnly 'org.junit.platform:junit-platform-launcher'. On Maven, the aggregate junit-jupiter artifact normally supplies what is needed, but mixing a JUnit 4 vintage engine with 5.x without configuration causes a related mismatch.
A test passes in the terminal but fails in VS Code. Environment divergence is the usual cause: a different working directory for relative file paths, environment variables set in one but not the other, or a JDK version difference between the terminal shell and the extension's configured runtime. Set the project's Java runtime through the Java Projects view or the java.configuration.runtimes setting so both paths agree.
Stop condition: if tests fail only when run in parallel or in a suite, and the cause is not obvious from the stack trace, treat it as a design problem in the production code (shared state, non-deterministic dependencies such as clocks and random generators) rather than a runner setting. Inject those dependencies instead of chasing ordering flags. If a build fails with class version errors that persist after confirming a consistent JDK, the problem is project configuration and warrants reading the full Maven or Gradle output rather than adjusting editor settings.
Sources and coverage at a glance
The workflow above maps to the main failure surfaces:
| Symptom | Most likely cause | First check |
|---|---|---|
| No CodeLens links | Class not discovered | Filename suffix, location under src/test/java |
| Compile error on @Test | Wrong import or unresolved dependency | jupiter import; POM/Gradle file saved and reloaded |
| Build passes, zero tests run | Gradle missing useJUnitPlatform() | test { } block in build.gradle |
| Launcher "no tests found" | Missing test runtime launcher | Gradle testRuntimeOnly launcher dependency |
| Passes in terminal, fails in editor | Environment divergence | Working directory, env vars, configured JDK |
Questions that come up after the first test works
Should I write tests before the code? The workflow supports either order. Test-driven development, where you write the failing test first and then implement until it passes, works fine in VS Code because the runner reruns on demand; there is no automatic watch mode equivalent to some IDEs, so you rerun manually or from the Testing view.
How do I test private methods? You usually do not test them directly. Test them through the public methods that call them; if a private method is complex enough to warrant its own test, that is a signal to extract it into a package-private or separate collaborator class that the test can reach, since tests in the same package can call package-private methods.
Does this work for Spring Boot applications? Yes, and the Spring Boot test slice annotations (@SpringBootTest, @WebMvcTest) work with the same runner. The Spring Initializr generates a @SpringBootTest smoke test in src/test/java, which appears automatically in the Testing view once the project imports. Keep full-context tests few and focused, because each one starts an application context and the suite gets slow quickly.
What about JUnit 4 projects? The Vintage engine lets the JUnit 5 platform run JUnit 4 tests alongside Jupiter tests, but mixing both styles in one project creates import confusion. If the project is JUnit 4 throughout, keep the JUnit 4 dependency and runner configuration consistent rather than migrating mid-stream.