4

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

2 Answers 2

2

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

@SpringBootTest(classes = {EmployeeRepository.class,EmployeeService.class})
Sign up to request clarification or add additional context in comments.

Comments

1

Usually to test the service layer, it is not necessary to use Spring Test framework. You can mock all beans used by your service except if you really need Spring context.

@RunWith(MockitoJUnitRunner.class)
public class EmployeeServiceImplTest {

    @Mock
    private EmployeeRepository employeeRepository;

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

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.