Spring Boot & H2 - 单元测试存储库



概述

要测试存储库,我们需要以下注释和类:

  • @ExtendWith(SpringExtension.class) - 使用 SpringExtension 类标记为测试用例运行的类。

  • @SpringBootTest(classes = SprintBootH2Application.class) - 配置 Spring Boot 应用程序。

  • @Transactional - 标记存储库以执行 CRUD 操作。

  • @Autowired private EmployeeRepository employeeRepository - 要测试的 EmployeeRepository 对象。

EmployeeRepositoryTest.java

以下为 EmployeeRepositoryTest 类的完整代码。

package com.tutorialspoint.repository;

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

import java.util.ArrayList;
import java.util.List;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit.jupiter.SpringExtension;

import com.tutorialspoint.entity.Employee;
import com.tutorialspoint.springboot_h2.SpringbootH2Application;

import jakarta.transaction.Transactional;

@ExtendWith(SpringExtension.class)
@Transactional
@SpringBootTest(classes = SpringbootH2Application.class)
public class EmployeeRepositoryTest {

   @Autowired
   private EmployeeRepository employeeRepository;
   
   @Test
   public void testFindById() {
      Employee employee = getEmployee();	     
      employeeRepository.save(employee);
      Employee result = employeeRepository.findById(employee.getId()).get();
      assertEquals(employee.getId(), result.getId());	     
   }
   
   @Test
   public void testFindAll() {
      Employee employee = getEmployee();
      employeeRepository.save(employee);
      List<Employee> result = new ArrayList<>();
      employeeRepository.findAll().forEach(e -> result.add(e));
      assertEquals(result.size(), 1);	     
   }
   
   @Test
   public void testSave() {
      Employee employee = getEmployee();
      employeeRepository.save(employee);
      Employee found = employeeRepository.findById(employee.getId()).get();
      assertEquals(employee.getId(), found.getId());	     
   }
   
   @Test
   public void testDeleteById() {
      Employee employee = getEmployee();
      employeeRepository.save(employee);
      employeeRepository.deleteById(employee.getId());
      List<Employee> result = new ArrayList<>();
      employeeRepository.findAll().forEach(e -> result.add(e));
      assertEquals(result.size(), 0);
   }
   
   private Employee getEmployee() {
      Employee employee = new Employee();
      employee.setId(1);
      employee.setName("Mahesh");
      employee.setAge(30);
      employee.setEmail("[email protected]");
      return employee;
   }
}

运行测试用例。

在 Eclipse 中右键单击文件并选择 运行 JUnit 测试,然后验证结果。

Repository Test Result
广告