在执行单元测试时,Spring Boot 应用是否需要连接数据库?

huangapple go评论103阅读模式
英文:

Is it required for spring boot application to be connected to database when performing unit test

问题

以下是您提供的内容的翻译部分:

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

@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);
    }
}

我正在为我的数据库(PostgreSQL)使用Docker镜像。当数据库容器启动后,上述测试用例可以成功运行。

但是,当我停止整个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 吗?

想象一个人在他们的机器上首次检出此代码,并在设置数据库之前首先构建项目。在这种情况下,单元测试应该运行,并且不应依赖于数据库。

请注意,我正在使用 JUnit 5(Jupiter)和 spring-boot-starter-test 工具包。

英文:

I am writing unit test cases for service layer. This is my service class:

@Service
@RequiredArgsConstructor
public class EmpService {

    private final EmpRepository empRepository;

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

Test class:

@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);
    }
}

I am using docker images for my database (postgres). When the container is up for db, then the above test case runs successfully.

But when I stop the whole docker application, in that case it gives the following error:

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

Shouldn't the unit test cases be independent from database, specially when we are mocking the repo bean?

Imagine a person takes fresh checkout of this code on their machine and builds the project first without setting up the db. In that case the unit tests should run and should not be dependent on database.

Please note I am using JUnit 5 (Jupiter), spring-boot-starter-test kit.

答案1

得分: 1

依我看,你所写的更像是集成测试,而不是单元测试。

除了语义之外,有一个名为testcontainers的非常不错的框架,它可以在Docker容器中仅用于测试阶段运行数据库。

这里有一篇文章展示了如何设置这样的数据库测试:https://programmerfriend.com/spring-boot-integration-testing-done-right/

英文:

In my opinion, what you write is more integration test, than unit one.

Apart for semantics, there is very nice framework named testcontainers, that will run database in docker container just for tests phase.

Here is article that shows how to set up such database tests: https://programmerfriend.com/spring-boot-integration-testing-done-right/

huangapple
  • 本文由 发表于 2020年9月30日 19:34:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/64136740.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定