Next-Gen App & Browser Testing Cloud
Trusted by 2 Mn+ QAs & Devs to accelerate their release cycles

Learn how to perform Java unit testing using JUnit with step-by-step guidance on setup, writing test cases, and ensuring your code works as expected.
Deboshree
December 28, 2025
Unit testing is a technique where individual units or components of software are tested in isolation using different programming languages. For Java unit testing, JUnit is the widely used framework, providing annotations and assertions that streamline the process of writing and running unit tests.
Java unit testing is the process of writing tests in Java to check whether small units of your code (typically methods or classes) work as expected.
Steps to Perform Java Unit Testing
JUnit is the default testing framework for Java. It’s lightweight, extensible, and supported by every major IDE and CI/CD tool.
Features:
If you are getting started with JUnit, we recommend checking out this JUnit tutorial.
To get started, make sure you have the following:
Maven: To use Maven, add the following to the pom.xml file:
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.8.2</version>
<scope>test</scope>
</dependency>
</dependencies>
Gradle: For Gradle, add the following to the build.gradle file:
dependencies {
testImplementation 'org.junit.jupiter:junit-jupiter:5.8.2'
}
test {
useJUnitPlatform()
}
Let’s walk through the process of writing a basic unit test in Java.
Test Scenario:
Verify that a basic calculator performs arithmetic operations: addition, subtraction, multiplication, and division.
Here’s the Calculator class:
public class Calculator {
public int add(int a, int b) {
return a + b;
}
public int subtract(int a, int b) {
return a - b;
}
public double divide(int a, int b) {
if (b == 0) throw new IllegalArgumentException("Cannot divide by zero");
return (double) a / b;
}
}

Implementation:
Let’s write unit tests to verify the basic arithmetic operations (addition, subtraction, multiplication, and division). It includes edge cases like zero and negative numbers and ensures exceptions are thrown for invalid operations like division by zero.
@DisplayName("Calculator Tests")
class CalculatorTest {
private final Calculator calculator = new Calculator();
@Test
@DisplayName("Test addition with zero")
void testAddWithZero() {
assertEquals(5, calculator.add(5, 0));
assertEquals(5, calculator.add(0, 5));
assertEquals(0, calculator.add(0, 0));
}
@Test
@DisplayName("Test addition with negative numbers")
void testAddWithNegativeNumbers() {
assertEquals(-8, calculator.add(-5, -3));
assertEquals(2, calculator.add(5, -3));
assertEquals(-2, calculator.add(-5, 3));
}
@Test
@DisplayName("Test subtraction with zero")
void testSubtractWithZero() {
assertEquals(5, calculator.subtract(5, 0));
assertEquals(-5, calculator.subtract(0, 5));
assertEquals(0, calculator.subtract(0, 0));
}
@Test
@DisplayName("Test subtraction with negative numbers")
void testSubtractWithNegativeNumbers() {
assertEquals(-2, calculator.subtract(-5, -3));
assertEquals(8, calculator.subtract(5, -3));
assertEquals(-8, calculator.subtract(-5, 3));
}
@Test
@DisplayName("Test multiplication with zero")
void testMultiplyWithZero() {
assertEquals(0, calculator.multiply(5, 0));
assertEquals(0, calculator.multiply(0, 5));
assertEquals(0, calculator.multiply(0, 0));
}
@Test
@DisplayName("Test multiplication with negative numbers")
void testMultiplyWithNegativeNumbers() {
assertEquals(15, calculator.multiply(-5, -3));
assertEquals(-15, calculator.multiply(5, -3));
assertEquals(-15, calculator.multiply(-5, 3));
}
@Test
@DisplayName("Test division by zero")
void testDivideByZero() {
assertThrows(IllegalArgumentException.class, () -> calculator.divide(5, 0));
}
@Test
@DisplayName("Test division with zero numerator")
void testDivideWithZeroNumerator() {
assertEquals(0.0, calculator.divide(0, 5));
}
@Test
@DisplayName("Test division with negative numbers")
void testDivideWithNegativeNumbers() {
assertEquals(1.6666666666666667, calculator.divide(-5, -3));
assertEquals(-1.6666666666666667, calculator.divide(5, -3));
assertEquals(-1.6666666666666667, calculator.divide(-5, 3));
}
}
Code Walkthrough:
Test Execution:
Run the below command to execute the test:
mvn test -Dtest=CalculatorTest

While unit tests validate your logic in isolation, they don’t ensure that your web application behaves as intended across browsers. That’s where UI testing comes in.
By using Selenium, you can simulate user interactions, and with JUnit, you get features like annotations and assertions for structuring and executing test cases. When combining Selenium with JUnit, you can automate your tests across browsers to ensure your web application behaves as intended at the user interface level.
Test Scenario:
Implementation:
To run this test, make sure you’ve added the following Selenium dependency in your pom.xml file:
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.15.0</version>
</dependency>
Below is the test script that uses Selenium to automate the behavior of a simple calculator UI.
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@DisplayName("Calculator Addition Tests")
public class LocalSeleniumCalculatorTest {
private WebDriver driver;
@BeforeAll
void setUp() {
driver = new ChromeDriver();
driver.manage().window().maximize();
}
@AfterAll
void tearDown() {
if (driver != null) {
driver.quit();
}
}
@ParameterizedTest(name = "Test Case {index}: {0} + {1} = {2}")
@CsvSource({
"5, 7, 12",
"1, 1, 2",
"-2, 3, 1",
"100, 200, 300",
"1000000, 2000000, 3000000",
"999999, 1, 1000000",
"abc, def, Entered value is not a number",
"xyz, 123, Entered value is not a number",
"2147483647, 1, 2147483648",
"'', '', Entered value is not a number",
"' ', ' ', Entered value is not a number"
})
@DisplayName("Test calculator addition with various inputs")
void testAddition(String a, String b, String expected) {
driver.get(TestConfig.APP_URL);
WebElement firstInput = driver.findElement(By.id("sum1"));
WebElement secondInput = driver.findElement(By.id("sum2"));
WebElement getSumButton = driver.findElement(By.xpath("//button[text()='Get Sum']"));
firstInput.clear();
firstInput.sendKeys(a);
secondInput.clear();
secondInput.sendKeys(b);
getSumButton.click();
WebElement result = driver.findElement(By.id("addmessage"));
assertEquals(expected, result.getText());
}
}
Code Walkthrough:
Test Execution:
Run the below command to execute the test:
mvn test -Dtest=LocalSeleniumCalculatorTest

Running UI tests locally is a great starting point. However, to catch layout bugs, inconsistent DOM behavior, and platform-specific quirks, you need cross-browser testing, and that’s where TestMu AI comes in.
TestMu AI is a GenAI-native test execution platform that provides an online Selenium Grid to run JUnit tests across multiple browsers and OS combinations without maintaining your infrastructure.
To get started, check out this documentation on JUnit testing on TestMu AI.
To run Selenium JUnit tests on TestMu AI instead of your local machine, you need to replace the local WebDriver instance with a RemoteWebDriver that connects to TestMu AI cloud Selenium Grid using the URL https://
After that, you need to configure Selenium automation capabilities to define the browser, version, platform, and other settings.
You can generate these capabilities from the TestMu AI Automation Capabilities Generator.
Test Execution:
Run the below command to execute the test:
mvn test -Dtest=CloudCalculatorTest

Here are some of the best practices you can follow while performing Java unit testing:
Looking to speed up and simplify your test creation process? Explore how AI unit test generation can automate and enhance your Java testing workflow.
By now, you’ve seen how JUnit can streamline your testing workflow by writing clear, maintainable unit tests. We have also seen how you can scale JUnit tests with tools like Selenium and perform Java unit testing in the cloud. This approach not only saves time and reduces bugs but also helps you ship with confidence, knowing your code is tested and reliable.
Did you find this page helpful?
More Related Hubs
TestMu AI forEnterprise
Get access to solutions built on Enterprise
grade security, privacy, & compliance