Unit Testing for Java

Unit Testing for Java

By - Pooja Bhavsar5/27/2025

Unit testing is a software testing technique where individual units or components of a program are tested independently to ensure they perform as expected. A "unit" typically refers to the smallest testable part of an application, like a function, method, or class. Learn Unit Testing for Java with key frameworks like JUnit. Understand test cases, best practices, and how to improve code quality in Java applications.

 

In unit testing, each test targets a specific part of the code, often without relying on other parts of the system. For example, a test might check whether a function correctly calculates the sum of two numbers or whether a class method updates a value accurately. By isolating each part, developers can pinpoint issues more efficiently and fix bugs before they become harder and more costly to resolve.

 

Automated unit tests are usually written by developers during the development process. These tests can be run repeatedly, especially after changes or additions to the codebase. This not only helps in verifying new code but also ensures that existing functionality remains unaffected—a concept known as regression testing.

There are various frameworks available for unit testing in different programming languages. For example, JUnit is popular for Java, Google Test for C++, NUnit for .NET, and PyTest for Python. These tools provide built-in functions to assert expected outcomes, set up test environments, and report results clearly.

 

Purpose of Unit Testing

  • Verify the correctness of individual components.

     
  • Detect bugs early in the development cycle.

     
  • Simplify debugging, since tests are focused on small parts of the code.

     
  • Facilitate code refactoring with confidence that existing functionality won’t break.

     
  • Improve documentation, as tests demonstrate how the code is intended to work.

     

What is Unit Testing for Java?

In the context of Java development, unit testing ensures that each method or class performs as expected before integrating it into the larger system. By focusing on small, isolated pieces of functionality, developers can identify and fix bugs early, improve code design, and build more maintainable applications.

 

What Is a Unit in Java?

In Java, a unit usually refers to a single method or function within a class. For example, a method that calculates the area of a circle can be considered a unit. When this method is tested independently with various inputs, the process is called unit testing.

 

Why do we need to perform Unit Testing in Java?

Java is widely used for building enterprise applications, mobile apps (via Android), and web services. These applications often involve complex logic spread across many classes and methods. Without proper unit testing, small changes in one part of the code can inadvertently break functionality elsewhere.

 

Key reasons unit testing is crucial in Java:

  • Early Detection of Bugs: Developers can catch issues during development, long before the application goes into production.

     
  • Improved Code Quality: Writing unit tests encourages better coding practices, such as modular design and clear responsibilities.

     
  • Faster Refactoring: With a solid suite of tests, developers can confidently refactor code without fearing unexpected consequences.

     
  • Documentation: Unit tests serve as live documentation, showing how methods are intended to be used.

 

JUnit – The Standard Unit Testing Framework in Java

JUnit is the most popular framework for unit testing in Java. It provides annotations, assertions, and test runners to create and execute tests efficiently.

 

Key Annotations in JUnit 5:

  • @Test: Marks a method as a test case.

     
  • @BeforeEach: Runs before each test method.

     
  • @AfterEach: Runs after each test method.

     
  • @BeforeAll: Runs once before all tests in the class.

     
  • @AfterAll: Runs once after all tests.

     
  • @DisplayName: Describes the test method for better readability.

     

Common Assertions:

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

     
  • assertTrue(condition): Checks if a condition is true.

     
  • assertThrows(): Confirms that a specific exception is thrown.

     
  • assertNotNull(object): Checks that an object is not null.

     

Example:

 Calculator.java

 

public class Calculator {

 

    public int add(int a, int b) {

        return a + b;

    }

 

    public int subtract(int a, int b) {

        return a - b;

    }

 

    public int divide(int a, int b) {

        if (b == 0) {

            throw new IllegalArgumentException("Cannot divide by zero.");

        }

        return a / b;

    }

}

 

CalculatorTest.java

import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.*;

 

class CalculatorTest {

 

    Calculator calc = new Calculator();

 

    @Test

    void testAdd() {

        assertEquals(5, calc.add(2, 3));

        assertEquals(-1, calc.add(2, -3));

    }

 

    @Test

    void testSubtract() {

        assertEquals(1, calc.subtract(4, 3));

    }

 

    @Test

    void testDivide() {

        assertEquals(2, calc.divide(10, 5));

    }

 

    @Test

    void testDivideByZero() {

        assertThrows(IllegalArgumentException.class, () -> calc.divide(10, 0));

    }

}

 

Explanation:

  • We test the add, subtract, and divide methods with valid inputs.

     
  • We also test the divide method to ensure it throws an exception when dividing by zero.

     
  • These tests help verify the correctness and robustness of the Calculator class.

 

Performing Unit Testing on Springboot Application

Step 1. Create a springboot project from Spring Initializer, having dependencies like MySQL Connector, Spring Data JPA, Spring Web

Step 2: Import that project into an IDE like STS or IntelliJ IDEA

Step 3: Create Controller, Entity, Service , Repository inside src=> main=> java

Person.java(Entity)

package com.unitTest.UnitTesting_Demo.entities;

import jakarta.persistence.Entity;

import jakarta.persistence.Id;

 

@Entity

public class Person {

   @Id

   private Integer personId;

   private String personName;

   private String personCity;

 

   public Person(Integer personId, String personName, String personCity) {

       this.personId = personId;

       this.personName = personName;

       this.personCity = personCity;

   }

   public Person() {

   }

}

PersonRepo.java(Repository)

package com.unitTest.UnitTesting_Demo.repo;

 

import com.unitTest.UnitTesting_Demo.entities.Person;

import org.springframework.data.jpa.repository.JpaRepository;

import org.springframework.data.jpa.repository.Query;

import org.springframework.data.repository.query.Param;

 

public interface PersonRepo extends JpaRepository<Person, Integer> {

 

      @Query("SELECT CASE WHEN COUNT(p) > 0 THEN TRUE ELSE FALSE END FROM Person p WHERE p.personId = :id")

      Boolean isPersonExistsById(@Param("id") Integer id);

}

Explore Other Demanding Courses

No courses available for the selected domain.

PersonService.java( Service )

package com.unitTest.UnitTesting_Demo.services;

import com.unitTest.UnitTesting_Demo.entities.Person;

import com.unitTest.UnitTesting_Demo.repo.PersonRepo;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

import java.util.List;

@Service

public class PersonService {

       @Autowired

        private PersonRepo  personRepo;

 

       public List<Person> getAllPersons()

       {

           return this.personRepo.findAll();

       }

 

   public PersonService(PersonRepo personRepo) {

       this.personRepo = personRepo;

   }

}

PersonController.java( Controller )

package com.unitTest.UnitTesting_Demo.controller;

 

import com.unitTest.UnitTesting_Demo.services.PersonService;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.http.ResponseEntity;

import org.springframework.web.bind.annotation.GetMapping;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.ResponseBody;

import org.springframework.web.bind.annotation.RestController;

 

@RestController

public class MyController {

 

   @Autowired

   private PersonService  personService;

 

   @RequestMapping("/")

   @ResponseBody

   public String demo()

   {

       return  "hello java";

   }

 

   @RequestMapping("/persons")

   public ResponseEntity<?> getAllPersons()

   {

           return  ResponseEntity.ok(this.personService.getAllPersons());

   }

 

}

In above code, we are now going to test PersonRepo and PersonService. 

 

Testing of PersonRepo

So in src=> test=> java create new package “repo”  and in that package, create class PersonRepoTest. In PersonRepoTest we are going to test whether the given id is exists in database or not. If the id is exists then the test case will get pass otherwise test case will get fail.

PersonRepoTest.java

package com.unitTest.UnitTesting_Demo.repo;

 

import com.unitTest.UnitTesting_Demo.entities.Person;

import org.junit.jupiter.api.AfterEach;

import org.junit.jupiter.api.BeforeEach;

import org.junit.jupiter.api.Test;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.boot.test.context.SpringBootTest;

 

import static org.assertj.core.api.AssertionsForClassTypes.assertThat;

import static org.junit.jupiter.api.Assertions.*;

@SpringBootTest

class PersonRepoTest {

   @Autowired

   private PersonRepo personRepo;

   @Test

   void isPersonExistsById()

   {

       Person person=new Person(1234,"ram","delhi");

       personRepo.save(person)

     Boolean actualResult=personRepo.isPersonExistsById(1234);

       assertThat(actualResult).isTrue();

   }

   @AfterEach

   void tearDown() {

       System.out.println("in tearDown");

       personRepo.deleteAll();

   }

   @BeforeEach

   void setUp() {

       System.out.println("in setUp");

   }

}

 

@Test => the method annotated with @Test annotation consists of test cases(means, the part of code which we wants to test).

@AfterEach =>  the method annotated with @AfterEach annotation can execute after each test case.

@BeforeEach =>  the method annotated with @BeforeEach annotation can execute before each test case

 

Testing of PersonService

So in src=> test=> java create new package “services”  and in that package, create class PersonServiceTest. In PersonServiceTest we are going to test whether the findAll() method in PersonRepo gives exactly same result as the findAll() method present in PersonService

package com.unitTest.UnitTesting_Demo.services;

import com.unitTest.UnitTesting_Demo.entities.Person;

import com.unitTest.UnitTesting_Demo.repo.PersonRepo;

Import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

import java.util.List;

 

@Service

public class PersonService {

 

        @Autowired

        private PersonRepo  personRepo;

       public List<Person> getAllPersons()

       {

           return this.personRepo.findAll();

       }

   public PersonService(PersonRepo personRepo) {

       this.personRepo = personRepo;

   }

}

PersonServiceTest.java

 

package com.unitTest.UnitTesting_Demo.services;

 

import com.unitTest.UnitTesting_Demo.repo.PersonRepo;

import org.junit.jupiter.api.BeforeEach;

import org.junit.jupiter.api.Test;

import org.junit.jupiter.api.parallel.Execution;

import org.mockito.Mock;

import org.mockito.junit.jupiter.MockitoExtension;

import org.springframework.beans.factory.annotation.Autowired;

 

import static org.junit.jupiter.api.Assertions.*;

import static org.mockito.Mockito.verify;

 

@Execution(MockitoExtension.class)

class PersonServiceTest {

 

   @Mock

   private PersonRepo personRepo;

 

   private PersonService personService;

 

   @BeforeEach

   void setUp() {

        this.personService= new PersonService(this.personRepo);

   }

 

   @Test

   void getAllPersons()  //here we don't need to test repo..only we have to test service but service internally uses repo and hence we need to use mockito here

   {

     personService.getAllPersons();

 

     verify(personRepo).findAll();

 

   }

}

Do visit our channel to learn more: SevenMentor

 

Author:-

Pooja Bhavsar

Get Free Consultation

Loading...

Call the Trainer and Book your free demo Class..... Call now!!!

| SevenMentor Pvt Ltd.

© Copyright 2025 | SevenMentor Pvt Ltd.

Share on FacebookShare on TwitterVisit InstagramShare on LinkedIn