Writing Service and Repository Layer Tests for JPA RESTful API in Springboot

Intro

I’m writing tests for a RESTful JPA Springboot API but I am struggling to set it up. I have set a simple model, repository and service layer

Model

package id.ac.ui.cs.advpro.app.models;

import jakarta.persistence.*;
import jakarta.validation.constraints.*;
import lombok.*;

import java.util.Date;

@Entity
@Table(name = "transactions")
public class TransactionModel {

    @Id
    @GeneratedValue(strategy = jakarta.persistence.GenerationType.IDENTITY)
    @Column(name = "id")
    @NotNull
    @Setter
    @Getter
    private long id;

    @Column(name = "voucher_id")
    @Setter
    @Getter
    private long voucherId;

    @Column(name = "transaction_date")
    @NotNull
    @Setter
    @Getter
    private Date transactionDate;

    @Column(name = "total_amount")
    @NotNull
    @Setter
    @Getter
    private long totalAmount;

    public TransactionModel() {
    }

    public TransactionModel(long id, long voucherId, Date transactionDate, long totalAmount) {
        this.id = id;
        this.voucherId = voucherId;
        this.transactionDate = transactionDate;
        this.totalAmount = totalAmount;
    }
}

Repository

package id.ac.ui.cs.advpro.app.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import id.ac.ui.cs.advpro.app.models.TransactionModel;

@Repository
public interface TransactionRepository extends JpaRepository<TransactionModel, Long>{
}

Service

package id.ac.ui.cs.advpro.app.service.impl;

import java.util.List;
import java.util.Optional;

import org.springframework.stereotype.Service;
import id.ac.ui.cs.advpro.app.models.TransactionModel;
import id.ac.ui.cs.advpro.app.repository.TransactionRepository;
import id.ac.ui.cs.advpro.app.service.TransactionService;

@Service
public class TransactionServiceImpl implements TransactionService{

    private final TransactionRepository repository;

    public TransactionServiceImpl(TransactionRepository repository) {
        this.repository = repository;
    }

    //C(reate)
    @Override
    public TransactionModel addTransaction(TransactionModel transaction) {
        return repository.save(transaction);
    };

    //R(ead)
    @Override
    public List<TransactionModel> findAllTransaction() {
        return repository.findAll();
    };

    @Override
    public Optional<TransactionModel> findById(Long id) {
        return repository.findById(id);
    };

    //U(pdate)
    @Override
    public TransactionModel updateTransaction(TransactionModel transaction) {
        return repository.save(transaction);
    };

    //D(elete)
    @Override
    public void deleteTransaction(Long id) {
        repository.deleteById(id);
    };
}

Attempts

Here are my attempts at making tests for the service layer. I have looked into previously answered and suggested solutions here but none seem to work.

package id.ac.ui.cs.advpro.app.service.impl;
import id.ac.ui.cs.advpro.app.models.TransactionModel;
import id.ac.ui.cs.advpro.app.repository.TransactionRepository;

import java.util.Date;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.Assertions;


import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.InjectMocks;
import org.mockito.Spy;


@ExtendWith(MockitoExtension.class)
public class TransactionServiceImplTest {

    @InjectMocks
    private TransactionServiceImpl transactionService;

    @Spy
    private TransactionRepository transactionRepository;

    @BeforeEach
    public void setUp() {
        TransactionModel transaction = new TransactionModel(1, 1, new Date(), 100000);
        transactionService.addTransaction(transaction);
    }

    @Test
    public void testGetAllTransactions() {
        Assertions.assertEquals(1, transactionService.findAllTransaction().size());
    }
}

the test class successfully injected the repository into the service class but

transactionService.addTransaction(transaction);

returns null, it calls

repository.save(transaction);

which the docs said should never return null.

<TransactionModel> TransactionModel org.springframework.data.repository.CrudRepository.save(TransactionModel entity)
Saves a given entity. Use the returned instance for further operations as the save operation might have changed the entity instance completely.

Type Parameters:

Parameters:

entity must not be null.
Returns:

the saved entity; will never be null.
Throws:

IllegalArgumentException - in case the given entity is null.
OptimisticLockingFailureException - when the entity uses optimistic locking and has a version attribute with a different value from that found in the persistence store. Also thrown if the entity is assumed to be present but does not exist in the database.

thus the test fails because nothing is added to the repository.

Question

How should I write tests for the repository and service layers for my project?

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật