Search code examples
javadatabasespring-bootjunit5hikaricp

How to avoid database connection while testing service layer in spring boot application with Junit5


I am trying to unit test a service method which internally calls a repository method. My Test method is as follows:-

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

What I am asking is not a issue actually. When I am running my above, Spring boot application starts up and trying to create hikari pool initialization using DB connection.

How can I avoid this as it's unit test and I am mocking the repository and not interacting with database.

Thanks


Solution

  • Maybe u can try to load only the classes that u need to load by adding

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