gpt4 book ai didi

java - spring boot 应用程序在进行单元测试时是否需要连接数据库

转载 作者:行者123 更新时间:2023-12-05 06:11:06 26 4
gpt4 key购买 nike

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

@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

单元测试用例不应该独立于数据库,特别是当我们模拟 repo bean 时?

想象一个人在他们的机器上重新 checkout 这段代码,并在没有设置数据库的情况下首先构建项目。在这种情况下,单元测试应该运行并且不应依赖于数据库。

请注意,我使用的是 JUnit 5 (Jupiter),spring-boot-starter-test 套件。

最佳答案

在我看来,你写的更多是集成测试,而不是第一单元。

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

这是一篇介绍如何设置此类数据库测试的文章:https://programmerfriend.com/spring-boot-integration-testing-done-right/

关于java - spring boot 应用程序在进行单元测试时是否需要连接数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64136740/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com