使用Junit5在Spring Boot应用程序中测试服务层时如何避免数据库连接

问题描述

我正在尝试对内部调用存储库方法的服务方法进行单元测试。我的测试方法如下:-

@SpringBoottest
public class EmployeeServiceImpltest {

    @MockBean
    private EmployeeRepository employeeRepository;

    @Autowired
    private EmployeeService employeeService;

    private static Employee emp;

    @BeforeAll
    static void setup() {
        emp = new Employee(99,"TestUser");
    }

    @Test
    public void listAllEmployeestest() throws Exception {
        List<Employee> allEmployee = Arrays.asList(employee);
        Mockito.when(employeeRepository.findAll()).thenReturn(allEmployee);
        List<Employee> employeeList = (List<Employee>) cashierService.listAllEmployee();
        Assertions.assertIterableEquals(allEmployee,employeeList);
    }
}

我要问的实际上不是问题。当我在上面运行时,Spring启动应用程序启动并尝试使用数据库连接来创建hikari池初始化。

由于它是单元测试,并且在模拟存储库而不与数据库交互,因此如何避免这种情况。

谢谢

解决方法

通常测试服务层,没有必要使用Spring Test框架。您可以模拟服务使用的所有bean,除非您确实需要Spring上下文。

@RunWith(MockitoJUnitRunner.class)
public class EmployeeServiceImplTest {

    @Mock
    private EmployeeRepository employeeRepository;

    @InjectMocks
    private EmployeeService employeeService;

    private static Employee emp;

    @BeforeAll
    static void setup() {
        emp = new Employee(99,"TestUser");
    }

    @Test
    public void listAllEmployeesTest() throws Exception {
        List<Employee> allEmployee = Arrays.asList(employee);
        Mockito.when(employeeRepository.findAll()).thenReturn(allEmployee);
        List<Employee> employeeList = (List<Employee>) cashierService.listAllEmployee();
        Assertions.assertIterableEquals(allEmployee,employeeList);
    }

}
,

也许您可以尝试通过添加来仅加载您需要加载的类

@SpringBootTest(classes = {EmployeeRepository.class,EmployeeService.class})