Articles

What is JUnit Testing and How to Use It

What is JUnit?

JUnit is a framework in Java that makes unit testing easy and repeatable. It provides a set of annotations and assertions that help developers in writing test methods, and then run them automatically to check if the code behaves as expected. Instead of manually checking outputs, JUnit handles the execution and reports back with results showing what passed and what failed.

Behind the scenes, JUnit works by detecting and running methods marked as tests, comparing the actual output of the code with the expected output defined in assertions. If everything matches, the test passes, and if not, JUnit immediately flags the problem. This fast feedback loop helps developers catch issues early and maintain confidence as the codebase grows.

Now that we know what JUnit is and how it works, let’s step back and explore the broader concept it’s built to support.

What is unit testing?

Unit testing is the practice of checking the smallest parts of your code, like a single method or class, to be sure they behave as expected. Instead of waiting until the whole application is built, developers test these smaller parts early. This helps catch mistakes sooner, makes debugging simpler, and gives confidence that the code will behave correctly once it’s part of the larger system.

The real power of unit testing, however, emerges over time. With a suite of small, focused tests in place, developers can safely make changes or improvements to their code without fear of breaking existing functionality. These tests act like a safety net, running automatically to confirm that everything still works as intended.

This is exactly where JUnit becomes invaluable for Java developers. While unit testing provides the methodology, JUnit provides the tools and structure to make this testing approach both efficient and reliable in Java environments. Understanding this foundation helps explain why JUnit has become so essential in the Java development world.

Why use JUnit?

JUnit has become a go-to framework for Java developers because it makes testing both efficient and dependable. Instead of waiting until the very end of a project to uncover bugs, JUnit helps identify issues as soon as code is written or changed. This early feedback loop reduces time spent debugging and gives developers confidence that their code is behaving as expected.

Here are some key advantages of using JUnit:

  • Early bug detection: Problems surface quickly, saving time and cost in fixing them.

  • Automated regression testing: Every change in code can be validated without manual effort.

  • Smooth CI/CD integration: Works easily with Jenkins, GitHub Actions, and other automation tools to maintain code quality at scale.

With the “why” understood, let’s explore JUnit’s features.

Key features of JUnit testing in Java

JUnit offers a set of tools developers can use to write, run, and organize tests in a repeatable, automated way. The framework is built around two simple ideas: tell JUnit what to run and tell it how to verify results. Let’s break down the most common features and what each one does.

Annotations

Annotations are small markers you add to methods so JUnit knows how and when to run them. These are the key ones you will use most often:

  • @Test: Marks a method as a test case. JUnit will run this method and report success or failure based on the assertions inside it.

  • @BeforeEach: Runs before every test method in the class. Use it to set up a common test state so each test starts from a known place.

  • @AfterEach: Runs after every test method. Use it to clean up state, close resources, or reset singletons so tests do not interfere with one another.

  • @BeforeAll: Runs once before any tests in the class. It’s useful for an expensive setup that can be shared across tests, such as starting an embedded database or loading a large fixture.

  • @AfterAll: Runs once after all tests in the class have finished. Use it to tear down any global resources created in @BeforeAll.

Assertions

Assertions are how you express expected behavior in code. If an assertion fails, the test fails immediately. Common assertion methods include:

  • assertEquals(expected, actual): Verifies two values are equal.

  • assertTrue(condition): Verifies that a boolean condition is true.

  • assertFalse(condition): Verifies a boolean condition is false.

  • assertThrows(Exception.class, () -> { ... }): Verifies a block of code throws the expected exception.

  • assertNotNull(object): Verifies an object reference is not null.

  • assertArrayEquals(expectedArray, actualArray): Verifies two arrays contain the same elements in the same order.

Each assertion can optionally include a message to make test failures easier to diagnose.

Parameterized tests

Parameterized tests let you run the same test logic with different inputs without duplicating code. JUnit provides @ParameterizedTest along with input sources such as @ValueSource, @CsvSource, and @MethodSource. Use parameterized tests when you need to validate behavior across a range of values or combinations of inputs.

Test suites

Test suites let you group related tests and run them together as a single batch. That is useful when you want to run all unit tests for a module, or when you want to combine fast unit tests and slower integration tests into separate suites. Suites can be executed from your IDE or as part of your build and CI process.

These features give you a compact way to define what to test and how to check it. These tools are powerful, but how do you get JUnit running in the development environment?

How to set up JUnit in VS Code

Before writing your first test, you need to set up your environment with VS Code, Java, and JUnit. This ensures you can run and manage tests smoothly. The process of setting up JUnit in VS Code usually follows three steps:

  1. Install VS Code and JDK (Java Development Kit)

  2. Install VS Code extensions

  3. Add JUnit to your project (via JAR files or a build tool like Maven/Gradle)

Let’s explore each step in detail.

Step 1: Install VS Code and JDK (Java Development Kit)

  1. JUnit requires a working Java environment. So start by installing VS Code.

  2. Next, download the latest JDK from the Oracle JDK or OpenJDK site.

  • Install it and make sure it’s added to your system path.

  • Verify the installation by running:

java -version
javac -version

Step 2: Install VS Code extensions

To make VS Code ready for Java development and testing, install the following extensions:

  • Extension Pack for Java: Provides Java language support, project management, and debugging features.

VS Code marketplace showing the Extension Pack for Java being downloaded to set up JUnit Testing.

  • Test Runner for Java: Enables running JUnit tests directly from VS Code.

VS Code interface displaying the installation of the Test Runner for Java extension for running JUnit Testing.

Step 3: Add JUnit dependency to your project

Depending on your project setup, add JUnit to your project using one of the following methods:

  • For Maven projects: Add the JUnit dependency to your pom.xml file. For JUnit 5, this typically includes:

    • junit-jupiter-api
    • junit-jupiter-engine
    • junit-platform-launcher
  • For Gradle projects: Add the JUnit dependency in your build.gradle file.

  • Without a build tool: Manually download the JUnit JAR file (e.g., junit-platform-console-standalone.jar for JUnit 5) and add it to your project’s classpath, or you can also enable them within VS Code.

Once these steps are complete, your environment is ready to write and run tests. From here, you can start creating test classes and verify everything by running tests.

Writing your first JUnit test

Time to get hands-on. Let’s create a Java project in VS Code, write a basic Calculator class, enable JUnit, add test cases, and run them to see the results.

Step 1: Create a Java project in VS Code

Before we start writing tests, we need a Java project to work in. VS Code makes it easy to set up a basic Java project, even without build tools. Here’s how we can create a Java project in VS Code:

1. Press Ctrl+Shift+P and select Java: Create Java Project

VS Code command palette opened with Ctrl+Shift+P, selecting “Create Java Project” to prepare for JUnit Testing.

2. Choose No build tools

VS Code command palette opened with Ctrl+Shift+P, selecting “Create Java Project” to prepare for JUnit Testing.

3. Select the folder location for your project

4. VS Code creates a basic project with an App.java file

Project explorer in VS Code showing a newly created Java project, ready for JUnit Testing setup.

5. Rename App.java to Calculator.java

Step 2: Build the Calculator class

In Calculator.java, we will create a small class with basic arithmetic methods. This class will be the code we are testing, so we know exactly what output to expect from each method. Here’s the code:

public class Calculator {
public int add(int a, int b) {
return a + b;
}
public int divide(int a, int b) {
return a / b;
}
}

In this code:

  • add returns the sum of two numbers.
  • divide performs integer division and will throw an exception if dividing by zero, which we can test.

Step 3: Enable Java tests and add JUnit

Now that we have the code, we need to enable testing in VS Code and add the JUnit library. This lets us run tests directly from the IDE without manually managing JARs.

  1. Click on the Testing tab (The beaker icon) on the left-hand side
  2. Click Enable Java Tests
  3. Select JUnit when prompted

VS Code asking to enable Java tests, with JUnit framework selected for unit testing setup.

The following JAR files are added under the lib folder automatically:

  • hamcrest-core-1.3.jar
  • junit-4.13.2.jar

VS Code project lib folder displaying hamcrest-core.jar and junit.jar files automatically added for JUnit Testing.

Note: The versions of the .jar files may change

Step 4: Add the test file

Next, we create a test class to validate the behavior of our Calculator methods. We will have two test methods: one for addition and one for division by zero. Here’s how we can add a test file

1. Right-click your project and add a new file namedCalculatorTest.java

2. Add the following code:

import org.junit.Assert;
import org.junit.Test;
public class CalculatorTest {
@Test
public void testAddition() {
Calculator calculator = new Calculator();
int result = calculator.add(2, 3);
Assert.assertEquals(5, result);
}
@Test
public void testDivisionByZero() {
Calculator calculator = new Calculator();
try {
calculator.divide(1, 0);
Assert.fail("Division by zero should throw ArithmeticException");
} catch (ArithmeticException e) {
// Test passes
}
}
}

In this code:

  • @Test marks a method as a test. JUnit runs all methods with this annotation.
  • Assert.assertEquals checks that the output is correct.
  • Assert.fail() ensures the test fails if an exception is not thrown.

Step 5: Run the tests

Once the test class is ready, we can run our tests in VS Code or from the terminal to check if our methods work as expected.

1. Open the Testing tab in VS Code

2. Click the “run test” next to each method or the class to execute all tests

VS Code editor showing “Run Test” buttons next to methods and classes, enabling execution of JUnit Tests.

3. VS Code will display green check marks for passing tests and red crosses for failing tests

VS Code test explorer showing green check marks for passing JUnit Tests in a Java project.

Let’s change a value in one of the methods to see if the test fails:

VS Code test explorer showing red error indicators where JUnit Tests failed after modifying method values.

It shows that the testing failed due to the mismatch of the outputs.

Alternatively, run tests from the terminal using:

  • Maven: mvn test
  • Gradle: ./gradlew test

By following these steps, you now have a working Java project with JUnit tests running in VS Code. You can experiment with different inputs and see how test results help you catch errors early.

Let’s explore best practices for JUnit testing to write cleaner and more reliable test code.

Best practices for JUnit testing

Poorly written tests can slow down development and make debugging harder, so following some guidelines from the start will save you time and headaches later. Here are some practices to follow to ensure your JUnit tests are clean and effective:

  • Keep tests independent: Each test should run on its own and not depend on the result of another test. This ensures failures point directly to the problem.

  • Use descriptive test names: Name your test methods clearly to describe the behavior being tested, such as testAddition or testDivisionByZero. This makes it easier to understand what went wrong when a test fails.

  • Apply mocks and stubs when needed: For testing classes that rely on external systems or complex dependencies, use tools like Mockito to create controlled test environments.

  • Organize test code in parallel with production code: Mirror your code structure for easy maintenance.

With these best practices in place, your tests will be more reliable, readable, and easier to maintain. You’re now ready to apply JUnit effectively in any Java project.

Conclusion

JUnit helps Java developers write reliable, maintainable, and automated tests that catch bugs early and ensure code behaves as expected. By setting up JUnit in VS Code, writing test cases, and following best practices, you can streamline your testing workflow and make your code more robust. With JUnit, testing becomes an integral part of development rather than an afterthought.

For hands-on practice, explore the Codecademy Learn Intermediate Java: JUnit Testing course to strengthen your skills with real-world examples and automated testing techniques.

Frequently asked questions

1. What type of testing is JUnit used for?

JUnit is used for unit testing, which tests individual components or methods of a Java application to ensure they work correctly in isolation.

2. What is unit testing in Java?

Unit testing in Java is the process of verifying that each small part of your program, such as a method or class, functions as intended before integrating it into the larger application.

3. What is @Test in JUnit?

@Test is an annotation in JUnit that marks a method as a test case. JUnit automatically runs all methods with this annotation during testing.

4. How does JUnit run tests?

JUnit executes all test methods marked with @Test, checks the expected outcomes using assertions, and reports which tests pass or fail, helping developers identify issues quickly.

5. What is the purpose of JUnit?

The purpose of JUnit is to automate testing, catch errors early, improve code reliability, and provide a standardized framework for writing and running unit tests in Java.

6. Which is better, TestNG or JUnit?

Both are popular Java testing frameworks. JUnit is widely used and simpler for standard unit tests, while TestNG offers more advanced features like parallel test execution and flexible configuration. The choice depends on your project requirements.

Codecademy Team

'The Codecademy Team, composed of experienced educators and tech experts, is dedicated to making tech skills accessible to all. We empower learners worldwide with expert-reviewed content that develops and enhances the technical skills needed to advance and succeed in their careers.'

Meet the full team

Learn more on Codecademy