Member-only story

Comprehensive Guide to @Repository in Java with Mockito Unit Tests

Sanjay Singh
3 min readNov 29, 2024

Overview

The @Repository annotation in Spring Boot is a critical part of the persistence layer, allowing seamless integration with databases while promoting clean separation of concerns. This article dives into creating a robust EmployeeDao class to handle database operations using a JDBC connection and testing it effectively with Mockito. Whether you’re preparing for a coding interview or improving your database integration skills, this guide covers practical implementations with clear examples.

Comprehensive Guide to @Repository in Java with Mockito Unit Tests

Purpose

  1. Understand the use of @Repository in a Spring application.
  2. Implement CRUD operations with JDBC.
  3. Write unit tests for DAO classes using Mockito.

Table of Contents

  1. Introduction to @Repository
  2. Implementing EmployeeDao
  • Creating the DAO class
  • Methods: findEmployeeById and saveEmployee
  1. Writing Unit Tests for EmployeeDao
  • Mocking database connections
  • Verifying interactions with Connection, PreparedStatement, and ResultSet

1. Introduction to @Repository

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Sanjay Singh
Sanjay Singh

Written by Sanjay Singh

Java, Spring Boot & Microservices developer Sharing knowledge, tutorials & coding tips on my Medium page. Follow me for insights & see story list section

Responses (3)

Write a response

DAO Class Code

The findEmployeeById should return an Optional instead of returning "null" under some circumstances... Apart from implmenting such repository in the context of a spring application....

class EmployeeDaoTest {

Your coupling between your test and the implementation details of the EmployeeDao is too high because all checks "verify" (comment: "Verify connection usage)... are a bad idea... you are combining different levels of testing

Mockito Test Class

Why using a beforeEach (setup) method which creates the instance of EmployeeDao manually ... because you already used "@InjectMocks" so that's not needed....

Recommended from Medium

Lists

See more recommendations