Imagine a Java billing class with a method that gives a 10% discount on renewals over £500. During a refactor, a developer changes the condition from > to >=, so a renewal of exactly £500 now gets the discount too. Nothing crashes, and the bug can sit unnoticed until finance checks the invoices. A JUnit test that calls the method with £500 and uses assertEquals to check the price would fail on the next build, and the developer would see it before the code is merged.
This guide walks through setting up JUnit, writing tests with annotations and assertions, and running them from your IDE, Maven or Gradle, and CI. We also cover the setup mistakes that cause most early problems, and how to use JUnit with Selenium.
What Is JUnit?
JUnit is an open-source Java framework for writing and running repeatable unit tests. It belongs to the xUnit family of test frameworks and provides annotations, assertions, and test runners, so you can write a test, run it, and see the result in one place.
JUnit has four basic parts. Here is how they work together:
- Unit testing: Checks one method or component in isolation, so a failure points to a specific piece of code.
- Annotations: Mark which methods are tests and when setup and cleanup code runs, using @Test, @BeforeEach, and @AfterEach.
- Assertions: Compare actual results with expected values, using methods such as assertEquals and assertTrue.
- Test runners: Find the annotated methods, run them, and report which ones passed or failed.
How JUnit Fits into Unit Testing and TDD
Unit testing means checking one small piece of code, such as a single method, on its own. Test-driven development (TDD) builds on this by writing the test before the code. The cycle has three steps:
- Write a failing JUnit test (red).
- Write just enough code to pass it (green).
- Clean up the code (refactor).
Integration testing sits one level above. It checks that parts such as a service and its database work together. JUnit can run both kinds of tests, though it is used mostly for unit tests because they are fast.
Benefits of JUnit Testing in Java
JUnit is open source and fits easily into a normal Java workflow. Here are the key benefits of JUnit testing in Java:
- Faster feedback: Unit tests run in seconds, so you spot a broken change straight away.
- Confident refactoring: You can change code and re-run the suite to confirm nothing broke, which is automated regression testing.
- Easier maintenance: Writing testable code pushes you to split logic into small methods, which are simpler to read and change.
- Consistent structure: Every test follows the same pattern of annotations and assertions, so teams can read each other's tests easily.
- Tool support: JUnit runs natively in IntelliJ, Eclipse, Maven, and Gradle.
Integration testing sits one level above. It checks that parts such as a service and its database work together. You can write both kinds of tests in JUnit, but most teams use it for unit tests, since those run in seconds.
JUnit 5 Features and Extensions
JUnit 5 is a major rewrite of JUnit 4, not a small update. It splits the framework into modules, cleans up the annotations, and adds a proper extension model for modern Java projects. JUnit 4 is still common in older codebases, so you may meet both.
JUnit 5 Architecture: Platform, Jupiter, and Vintage
JUnit 5 is split into three modules. Each one has a clear job:
- Platform launches tests and gives IDEs and build tools a single entry point.
- Jupiter provides the annotations and programming model you write tests with.
- Vintage runs old JUnit 4 tests on the new platform during a migration.
A newer JUnit 6 line now exists too. Check the JUnit user guide for the current version.
Key JUnit 5 Features
The table shows the main differences between the two versions. The lists below explain the new features and extensions in more detail.
Here are the main new features in JUnit 5:
- Updated annotations: Clearer lifecycle annotations such as @BeforeEach, @AfterEach, @BeforeAll and @AfterAll replace the older @Before, @After, @BeforeClass and @AfterClass.
- Better naming and structure: @DisplayName gives tests readable names, and @Nested groups related tests inside inner classes.
- Parameterised tests: @ParameterizedTest runs the same test with different inputs, using sources such as @ValueSource or @CsvSource.
- Dynamic tests: @TestFactory generates tests at runtime, which helps with data-driven scenarios.
- Richer assertions: Methods such as assertAll, assertThrows, and assertTimeout let you write more precise checks.
- Assumptions: AssumeTrue, assumeFalse, and assumingThat skip a test when a condition is not met, such as running only on CI.
How the JUnit 5 Extension API Works
Before JUnit 5, you added shared behaviour with runners and rules, and a class could use only one runner. The Extension API replaces both, and a single test class can register several extensions at once. Here is how you work with it:
- Register with @ExtendWith: Add the annotation to a test class or method to switch an extension on.
- Use ready-made extensions: The Mockito extension creates your mocks before each test, and the Spring extension loads the application context for integration tests.
- Write your own: Implement a callback interface such as BeforeEachCallback or AfterAllCallback to add behaviour like logging or test data setup.
- Register in code when needed: @RegisterExtension lets you configure an extension programmatically for a specific test.
How to Set Up JUnit Testing
The setup depends on which JUnit version your project uses. In both cases, you can add JUnit through Maven or Gradle, or by placing the JAR files on your project classpath.
Setting Up JUnit 5 with Maven and Gradle
JUnit 5 is modular, so it relies on the Jupiter and Platform components. The single junit-jupiter dependency brings in both, and your tests use annotations from the org.junit.jupiter.api package.The examples below use version 5.11.0. On Java 17 or newer, you can switch to a 6.x version and the same tests run.
JUnit 5 does not run tests written with JUnit 4 imports such as org.junit.Test, unless you add the Vintage engine. This is a common setup mistake, because the build still passes when the runner finds no tests to execute.
Maven
Add this dependency to your pom.xml:
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.11.0</version>
<scope>test</scope>
</dependency>Maven needs Surefire 2.22.0 or newer to run JUnit 5. Older versions will not find your tests.
Gradle
Add this dependency to your build file, then enable the JUnit Platform:
dependencies { testImplementation 'org.junit.jupiter:junit-jupiter:5.11.0' }
test { useJUnitPlatform() }Without useJUnitPlatform(), Gradle will not detect JUnit 5 tests. The build may then report zero tests and still succeed.
Setting Up JUnit 4
JUnit 4 is the older version, but a lot of existing Java projects still depend on it. It comes as one JAR, and its annotations such as @Test, @Before, and @After live in the org.junit package.
Maven
Add this dependency to your pom.xml:
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>Gradle
Add this line to your build file. No extra configuration is needed.
testImplementation 'junit:junit:4.13.2'Do not mix org.junit.Test with JUnit 5 annotations in the same class. The tests will be skipped without any error, so pick one version per class.
JUnit Annotations Explained
Annotations tell the runner what each method is for. Each one below shows its JUnit 4 name, its JUnit 5 equivalent, and a small example.
@Before (JUnit 5: @BeforeEach)
@Before runs before every test method, so each test starts from a clean state. JUnit 5 renamed it to @BeforeEach.
// JUnit 4
@Before public void setUp() { calc = new PriceCalculator(); }
// JUnit 5
@BeforeEach void setUp() { calc = new PriceCalculator(); }@Test
@Test marks a method as a test case. The runner executes it and reports pass or fail. The name is the same in both versions, but it comes from org.junit.Test in JUnit 4 and from org.junit.jupiter.api.Test in JUnit 5.
@Test void discountApplied() { assertEquals(540.0, calc.renewal(600.0)); }JUnit 4 test methods must be public, while JUnit 5 methods can be package-private, as shown above.
@After (JUnit 5: @AfterEach)
@After runs after every test method, so use it to release resources or reset state. JUnit 5 renamed it to @AfterEach.
// JUnit 4
@After public void tearDown() { calc = null; }
// JUnit 5
@AfterEach void tearDown() { calc = null; }@BeforeClass (JUnit 5: @BeforeAll)
@BeforeClass runs once before any test in the class, which suits expensive setup such as starting a browser. The method must be static, and JUnit 5 renamed the annotation to @BeforeAll.
// JUnit 4
@BeforeClass public static void once() { System.out.println("start"); }
// JUnit 5
@BeforeAll static void once() { System.out.println("start"); }In JUnit 5, you can drop the static requirement by adding @TestInstance(PER_CLASS) to the class.
@AfterClass (JUnit 5: @AfterAll)
@AfterClass runs once after every test in the class has finished. It follows the same static rule as @BeforeClass, and JUnit 5 renamed it to @AfterAll.
// JUnit 4
@AfterClass public static void done() { System.out.println("end"); }
// JUnit 5
@AfterAll static void done() { System.out.println("end"); }@Ignore (JUnit 5: @Disabled)
@Ignore skips a test, and in both versions you can add a reason. JUnit 5 renamed it to @Disabled.
@Disabled("Waiting for pricing API fix")
@Test void futureRule() { }The execution order is the same in both versions. @BeforeClass (@BeforeAll) runs once, then @Before (@BeforeEach), the test and @After (@AfterEach) run for every test, and @AfterClass (@AfterAll) runs once at the end.
JUnit Assertions
Assertions check that your code produces the result you expected. When one fails, JUnit marks the test as failed and prints a message showing what went wrong, so you can find the problem quickly.
Assertions are static methods on a dedicated class, and the class depends on the version:
- JUnit 4: The methods come from org.junit.Assert.
- JUnit 5: The methods come from org.junit.jupiter.api.Assertions, which offers a broader and more flexible set.
In JUnit 5, import the class statically so you can call the methods by name. The snippet at the end of the next section shows the import line.
Common Assertions in JUnit 5
These are the methods you will use most often:
- assertEquals(): Checks that two values are equal.
- assertNotEquals(): Checks that two values are different.
- assertTrue(): Passes when the condition is true.
- assertFalse(): Passes when the condition is false.
- assertNull(): Passes when the object is null.
- assertNotNull(): Passes when the object is not null.
- assertThrows(): Checks that a specific exception is thrown.
- assertAll(): Groups several assertions and reports every failure together.
- assertTimeout(): Checks that a block of code finishes within a time limit.
- assumeTrue() and assumeFalse(): Skip the test, instead of failing it, when a condition is not met.
The snippet below uses all of them in one test class. It assumes the PriceCalculator class from the introduction, with renewal() and discountCode() methods, and it expects renewal() to throw an IllegalArgumentException for a negative amount:
import static org.junit.jupiter.api.Assertions.*;
import static org.junit.jupiter.api.Assumptions.*;
import java.time.Duration;
import org.junit.jupiter.api.Test;
class PriceCalculatorTest {
PriceCalculator calc = new PriceCalculator();
@Test
void assertionsOverview() {
assumeTrue(System.getenv("CI") != null); // skip the test outside CI
assertEquals(540.0, calc.renewal(600.0));
assertNotEquals(600.0, calc.renewal(600.0));
assertTrue(calc.renewal(600.0) < 600.0);
assertFalse(calc.renewal(100.0) < 100.0);
assertNull(calc.discountCode(100.0));
assertNotNull(calc.discountCode(600.0));
assertThrows(IllegalArgumentException.class, () -> calc.renewal(-1));
assertTimeout(Duration.ofMillis(200), () -> calc.renewal(600.0));
assertAll("renewal prices",
() -> assertEquals(100.0, calc.renewal(100.0)),
() -> assertEquals(540.0, calc.renewal(600.0)));
}
}A failing assertion shows both values, such as expected: <540.0> but was: <500.0>. You can also pass a message as the last argument in JUnit 5, which makes the failure easier to read.
How to Run JUnit Tests
You can run JUnit tests from your IDE, your build tool, and your CI server. The commands differ, but the results match.
Running JUnit Tests from the IDE
Both major IDEs can run a single method, a whole class, or a full package. Check these prerequisites first:
- A JDK and your IDE installed.
- A project with the JUnit dependency added.
- At least one test class with a @Test method.
IntelliJ IDEA
- Open the test class in the editor.
- Right-click the class name or a single method.
- Choose Run 'PriceCalculatorTest'.
Eclipse
- Open the test class in the editor.
- Right-click the class name.
- Choose Run As, then JUnit Test.
Running JUnit Tests with Maven and Gradle
Maven and Gradle compile your code and run the tests with a single command, and they can package the result as a later step. That makes them the natural way to run JUnit in a CI pipeline, because every machine runs the suite the same way.
Check these prerequisites before you start:
- A JDK is installed and JAVA_HOME points to it.
- Your build file has the JUnit dependency and, for Gradle, the useJUnitPlatform() setting from the setup section.
- Your test classes sit in src/test/java and use the right annotations.
Run Tests with Maven
Run the test phase from the project root. Maven compiles the code, runs every test it finds, and writes the results to target/surefire-reports.
mvn testRun Tests with Gradle
Run the test task through the Gradle wrapper. Gradle builds an HTML report you can open in a browser at build/reports/tests/test/index.html.
/gradlew testIn CI, the job step is the same command, and a failing test turns the build red. You can also add code coverage tools such as JaCoCo to see which lines your tests never touch. Our CI/CD automation guide covers the pipeline.
How to Perform JUnit Testing with Selenium
JUnit works well for browser automation. JUnit handles structure and assertions, and Selenium WebDriver drives the browser.
Add the selenium-java dependency first. The test below needs it to compile and run.
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.25.0</version>
<scope>test</scope>
</dependency>This login test checks one valid and one invalid case. Each test gets its own fresh browser, so the order of the tests cannot affect the result, and each one asserts its own outcome. It uses explicit waits:
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.time.Duration;
import org.junit.jupiter.api.*;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.*;
class LoginTest {
WebDriver driver;
WebDriverWait wait;
@BeforeEach void start() {
driver = new ChromeDriver();
wait = new WebDriverWait(driver, Duration.ofSeconds(10));
}
@Test void validLogin() {
login("qa@example.com", "correct-pass");
assertTrue(wait.until(ExpectedConditions.urlContains("/dashboard")));
}
@Test void invalidLogin() {
login("qa@example.com", "wrong");
WebElement err = wait.until(
ExpectedConditions.visibilityOfElementLocated(By.id("error")));
assertEquals("Invalid credentials", err.getText());
}
void login(String u, String p) {
driver.get("https://example.com/login");
driver.findElement(By.id("email")).sendKeys(u);
driver.findElement(By.id("password")).sendKeys(p);
driver.findElement(By.id("submit")).click();
}
@AfterEach void stop() { driver.quit(); }
}This is a sample. It assumes Chrome is installed, since Selenium 4 downloads the matching driver itself, and a login page at the placeholder URL whose fields have the IDs email, password, submit, and error. A valid login must land on a URL containing /dashboard. Change the URL and locators to match your own application. Four habits keep browser tests stable:
- Use explicit waits instead of fixed sleeps.
- Use IDs instead of long CSS chains that break on every redesign.
- Start every test with a fresh browser session, so one test cannot leave a logged-in state behind for the next.
- Assert a different result for each case, so a failed login cannot pass by accident.
Keep browser tests few and leave most checks at the unit level. Our look at how software testing is moving toward automation covers the wider picture.
How Frugal Testing Helps You Scale Java Test Automation
Frugal Testing helps engineering teams build and scale Java test automation on JUnit 5, using Maven or Gradle and CI pipelines. We set up the test automation framework, wire it into your build, and make sure tests run on every commit, so your team gets reliable feedback quickly.
Java suites rarely stall because of the framework itself. They usually stall on flaky tests, half-finished migrations from JUnit 4, and missing regression coverage. Our engagements focus on fixing those problems first, so the suite stays small, stable, and easy for your team to own.
What Our Java Test Automation Engagement Looks Like
Our engagement follows four steps. Here is what to expect:
- Audit the current suite and JUnit version.
- Set up the framework and CI wiring.
- Build a prioritised regression suite that runs on every commit.
- Hand over with documentation, so your team owns it.
Teams usually come to us when an in-house effort has stalled. We also offer automation QA services and QA outsourcing services for teams that want extra capacity.

Conclusion
JUnit gives Java teams a simple way to catch bugs early. You write small tests with annotations and assertions, run them from your IDE or build tool, and let CI repeat them on every change. Most trouble comes from setup details, such as mismatched imports.
A good place to start is one JUnit 5 test class running in CI this week. Add Selenium tests only for the key user journeys, and grow the suite where your last bug escaped. Small, reliable tests beat a large suite that nobody trusts.
People Also Ask (FAQs)
Q1. BDD vs TDD: What is the difference?
Ans: TDD drives design with small failing unit tests written first, while BDD describes behaviour in plain-language scenarios that business and QA teams can read. Many teams use both together.
Q2. What is a good code coverage target for JUnit tests?
Ans: Around 70 to 80 percent suits most teams. Chasing 100 percent encourages weak tests, so focus on critical business logic and review uncovered branches in your coverage report.
Q3. What is regression testing?
Ans: Regression testing means re-running existing tests after a change to confirm nothing that worked before has broken. This regression testing definition holds for any software, and JUnit automates it.
Q4. What is system integration testing, and can JUnit cover it?
Ans: System integration testing checks that whole systems, such as your application, payment gateway, and database, work together end to end. JUnit can drive some of it, though dedicated tools help.
Q5. How often should JUnit tests run in CI?
Ans: Run unit tests on every commit or pull request, since they finish in seconds. Schedule slower integration and Selenium suites nightly, so developers keep fast feedback without losing broader coverage.





