Issue
How to write JUnit Test cases for RestController, Service and DAO layer?
I've tried MockMvc
@RunWith(SpringRunner.class)
public class EmployeeControllerTest {
private MockMvc mockMvc;
private static List<Employee> employeeList;
@InjectMocks
EmployeeController employeeController;
@Mock
EmployeeRepository employeeRepository;
@Test
public void testGetAllEmployees() throws Exception {
Mockito.when(employeeRepository.findAll()).thenReturn(employeeList);
assertNotNull(employeeController.getAllEmployees());
mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/employees"))
.andExpect(MockMvcResultMatchers.status().isOk());
}
How can I verify the CRUD methods inside the rest controller and other layers ?
Solution
You can use @RunWith(MockitoJUnitRunner.class)
for unit testing with your Service Layer mocking your DAO Layer components. You don't need SpringRunner.class
for it.
@RunWith(MockitoJUnitRunner.class)
public class GatewayServiceImplTest {
@Mock
private GatewayRepository gatewayRepository;
@InjectMocks
private GatewayServiceImpl gatewayService;
@Test
public void create() {
val gateway = GatewayFactory.create(10);
when(gatewayRepository.save(gateway)).thenReturn(gateway);
gatewayService.create(gateway);
}
}
You can use @DataJpaTest
for integration testing with
your DAO Layer
@RunWith(SpringRunner.class)
@DataJpaTest
public class GatewayRepositoryIntegrationTest {
@Autowired
private TestEntityManager entityManager;
@Autowired
private GatewayRepository gatewayRepository;
// write test cases here
}
Check this article for getting more details about testing with Spring Boot
Answered By - eHayik