[英]How to write junit test cases for rest controller, service and dao layer using springboot?
How to write JUnit Test cases for RestController , Service and DAO layer ?如何为RestController 、 Service和DAO 层编写JUnit测试用例?
I've tried MockMvc
我试过
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 ?如何验证其余控制器和其他层内的CRUD方法?
You can use @RunWith(MockitoJUnitRunner.class)
for unit testing with your Service Layer mocking your DAO Layer components.您可以使用
@RunWith(MockitoJUnitRunner.class)
对@RunWith(MockitoJUnitRunner.class)
DAO 层组件的服务层进行单元测试。 You don't need SpringRunner.class
for it.你不需要
SpringRunner.class
。
@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您可以使用
@DataJpaTest
与您的DAO 层进行集成测试
@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查看本文以获取有关使用Spring Boot 进行测试的更多详细信息
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.