Writing Unit Tests in Java
In the Java programming language, unit testing means manually analyzing, debugging, and testing a small module, or individual portion of a large or small Java program’s source code, typically a user-defined method or class in Java. Unit testing tasks verify that the program’s source code performs the execution as expected by the programmer.

The most widely used unit testing framework in the Java programming language is JUnit 5.
A simple example of a simple unit testing method in Java.
Let’s assume that a Java user has a simple example of adding two different integer values in a Java program.
public class Total_value {
public int addition(int p, int q) {
return p + q;
}
public int subtraction(int p, int q) {
return p – q;
}
}
A JUnit 5 test in Java programming can be written like this.
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class Total_valueTest {
Total_value obj = new Total_value();
@Test
public void testAddition() {
int output = obj.addition(7, 9);
assertEquals(16, output);
}
@Test
public void testSubtraction() {
int output = obj.subtraction(11, 3);
assertEquals(8, output);
}
}
Common JUnit assertions used in Java.
Java provides its users with multiple useful JUnit assertion methods, which can be used by Java developers as per their needs.
assertEquals(9, output);
assertNotEquals(13, output);
assertTrue(isValid);
assertFalse(isExpired);
assertNull(value);
assertNotNull(value);
For a custom program test exception.
@Test
void shouldThrowExceptionForNegativeNumber() {
assertThrows(
IllegalArgumentException.class,
() -> total_value.total_value(-1)
);
}
Testing methods for different scenarios in a Java program.
A good unit program source code test in a Java program should include more information than just the happy path.
Example of testing methods for different scenarios.
public int division(int p, int q) {
if (q == 0) {
throw new IllegalArgumentException(“Here value cannot be divided by any zero value”);
}
return p / q;
}
Test.
@Test
void shouldDivision_Integer() {
assertEquals(7, divide_value.division(21, 3));
}
@Test
void shouldThrowExceptionWhenDividingByZero() {
assertThrows(
IllegalArgumentException.class,
() -> divide_value.division(79, 0)
);
}
Think about testing methods for different scenarios.
- Normal user input.
- Boundary values.
- Empty/null input value expressions.
- Invalid input expressions.
- Custom program exceptions.
- Different business scenario expression methods.
Arrange–Act–Assert unit testing method.
This provides a useful structured AAA method for unit testing in Java program source code.
@Test
void shouldTotal_valuePrice() {
// Here we define an Arrange method
Order order = new Order(88.0, 99.0);
// Here we define an Act method
double total = order.total_value();
// Here we define an Assert method
assertEquals(112.0, total_value);
}
Explanation of Arrange–Act–Assert unit testing.
- Arrange method — This prepares test data for a user-defined program.
- Act method — This executes the source code being tested against user-defined program source code.
- Assert method — This verifies an output result against user-defined program source code.
Testing the concept of dependencies with the Mockito framework.
When a user-defined class in a Java program depends on another class component, Java users generally don’t want their unit tests to call a real database or external service.
Example of dependencies with the Mockito framework.
class ClientService {
private final ClientRepository repository;
ClientService(ClientRepository repository) {
this.repository = repository;
}
User findClient(long id) {
return repository.findById(id);
}
}
Mockito dependencies with the framework.
@ExtendWith(MockitoExtension.class)
class ClientServiceTest {
@Mock
private UserRepository repository;
@InjectMocks
private ClientService clientService;
@Test
void shouldFindClient() {
Client client = new Client(109, “Siddhi”);
when(repository.findById(109))
.thenReturn(Client);
User output = clientService.findClient(109);
assertEquals(“Siddhi”, output.getName());
verify(repository).findById(109);
}
}
In this example, the UserRepository is mocked, so the test focuses on the ClientService.
Java Program Parameterized Test Concept.
If a Java developer needs to run a single program source code test with multiple user inputs, the JUnit 5 Java testing framework fully supports parameterized test methods.
@ParameterizedTest method
@CsvSource({
“7, 9, 3”,
“43, 32, 55”,
“1, 6, 4”
})
void shouldTotalIntegers(int p, int q, int expected) {
assertEquals(expected, Total.addition(p, q));
}
Following this concept here can avoid creating multiple, nearly identical test methods in a Java program.
Good unit-testing practices in Java program source code.
- Always keep your source code tests small and focused.
- Always manage your source code test behavior, avoiding focusing on implementation details.
- Provide descriptive names for your custom user tests.
- Follow the unit test method arrangement–act–assert concept.
- Manage each of your test methods independently of one another.
- Never make source code execution dependent on testing order.
- Never use the original database or external API in unit test source code.
- Manage and test both success and failure test scenarios if necessary.
- Always manage your program’s custom source code to fix and fast test errors.
- Use mock unit test methods only if they clearly define a method.
- Automatically run tests as part of your custom program source code build/CI process.
A style for naming a function in a Java program.
Let’s use this instead.
@Test
void Sampletest() { }
You can use it as you like.
@Test
void shouldRejectInvalidEmail() { }
Also.
@Test
void shouldReturnEmptyListWhenUserDoesNotExist() { }
The name of this test should clearly indicate the expected behavior.
Unit Testing Mindset Behavior in Basic Java Programs.
There’s an easy and simple way to think about a program’s source code testing method in Java.
Some input method input by the user
↓
When a user-defined custom method is executed
↓
Then the user defines the program source code behavior as expected.
A good unit test concept in a Java program is performed in a specific order when refactoring source code to address method smells. These tasks provide a testing safety net for Java users when they improve the design of a program without inadvertently modifying its behavior.

