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

Viewed 657

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 Answers
Related