Java 执行单元测试时,spring boot应用程序是否需要连接到数据库

Java 执行单元测试时,spring boot应用程序是否需要连接到数据库,java,spring-boot,jpa,junit,mockito,Java,Spring Boot,Jpa,Junit,Mockito,我正在为服务层编写单元测试用例。这是我的服务课: @Service @RequiredArgsConstructor public class EmpService { private final EmpRepository empRepository; public EmployeeDto findById(UUID id) { return empRepository.findById(id).map(this::mapToEmployeeDto);

我正在为服务层编写单元测试用例。这是我的服务课:

@Service
@RequiredArgsConstructor
public class EmpService {

    private final EmpRepository empRepository;

    public EmployeeDto findById(UUID id) {
        return empRepository.findById(id).map(this::mapToEmployeeDto);
    }
}
测试等级:

@SpringBootTest
class EmpServiceTest {
    @Autowired
    EmpService empService;
    
    @MockBean
    EmpRepository empRepository;
    
    @Test
    void get_employee_by_id_success_case() throws IOException {

        UUID empId = UUID.fromString("2ec828f5-35d5-4984-b783-fe0b3bb8fbef"); 
        EmployeeDto expectedEmp = new EmployeeDto(empId, "James");
        EmployeeEntity stubbedEmployee = new EmployeeEntity(empId, "James");
        when(empRepository.findById(any(UUID.class)))
            .thenReturn(Optional.of(stubbedEmployee));
        EmployeeDto actualEmp = empService.findById(empId);
        assertEquals(expectedEmp, actualEmp);
    }
}
我正在为我的数据库(postgres)使用docker图像。当容器启动db时,上述测试用例将成功运行

但是当我停止整个docker应用程序时,在这种情况下,它会给出以下错误:

java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'empRepository' defined in repo.EmpRepository defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Cannot resolve reference to bean 'jpaMappingContext' while setting bean property 'mappingContext'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaMappingContext': Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.exception.JDBCConnectionException: Unable to open JDBC Connection for DDL execution
单元测试用例不应该独立于数据库吗,特别是当我们模拟repobean时

假设有人在他们的机器上重新签出此代码,然后在不设置数据库的情况下首先构建项目。在这种情况下,单元测试应该运行,并且不应该依赖于数据库


请注意,我使用的是JUnit5(Jupiter),spring boot starter测试工具包。

在我看来,您编写的更多的是集成测试,而不是单元一

除了语义,还有一个非常好的框架,名为,它将在docker容器中运行数据库,只用于测试阶段


下面是一篇展示如何设置此类数据库测试的文章:

@Kayaman这是为了代码覆盖率。现在应用程序处于非常初级的阶段。随着时间的推移,更多的逻辑将被添加到其中。您可以认为测试是为了检查在一个愉快的场景中是否返回了正确的dto。尝试模拟EmpService。@MS-如果我这样做了,那么我将如何调用我要测试的方法来检查它。@SpringBootTest加载应用程序上下文,这就是bean创建失败的原因。