Developing Repository layer by following TDD approach

Testing Repository layer in isolation: -

In last chapter we learn how to write test case for Service Layer. 
So, after writing Service Class Test Case below scenario occurred: -

– Service layer test case fails as it need to fetch data with the help of Repository layer which is not yet implemented
• Write the Repository layer so that test case passes
• Before writing Repository Class write the Test Case class for it

To write Service layer test case, we will use Annotations:

Testing the Repository class: -

Web Layer

Service Layer

Repository Layer

Sample DB
(Not yet Implemented)

"Customer Management microservice" repository layer performs CRUD operation on Customer entity class. And the repository class extends JPARepository.
• if the repository class has to be tested, we need a database on which the CRUD operations can be
• In absence of a database the repository class functionality cannot be tested.

Below is the Customer entity with phoneNo as Id:

public class Customer {
private String phoneNo;
private String emailId;
private String address;
private String dob;
private String ssnId;
private String firstName;
private String lastName;
//setter and getter

Below is the repository with custom queries and method by properties:

public interface CustomerRepository extends JpaRepository<Customer, String>{

@Query("select e from Customer e where e.firstName=?1 and e.lastName=?2 and e.ssnId=?3")
Customer getCustDetails(String firstName, String lastName, String ssnId);

Customer findByPhoneNo(String phoneNo);

@Query(nativeQuery=true, value="delete from customer where phoneNo=?1 and ssnId=?2")
int deleteCustDetails(String phoneNo,String ssnId);


Below is the testcase class and the setup needed for testing Repository layer:

public class CustomerRepositoryIntegrationTest {
private TestEntityManager entityManager;
private CustomerRepository cutomerRepository;

public void testGetCustDetailsPositive() {
cust.setAddress("#25, Millers Road, Bangalore");

//Inserting some sample data using TestEntityManager instance

//Testing our Repository class
Optional<Customer> found=custRepo.findById("9876536750");

– @RunWith(SpringRunner.class):Bridges SpringBoot Test and Junit
– @DataJpaTest provides certain setup required for testing the persistence layer:
o configuring H2, an in-memory database
o setting DataSource, Hibernate and the Spring Data.
o performing an @EntityScan

TestEntityManager :This autowired object which can be injected into a testcase class because we have annotated our class with @DataJpaTest.
This object can be used for prepopulating the database, so it is set up with some mockup data.