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