如何为 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());
}
我如何验证rest控制器和其他层中的 CRUD 方法?
答案 0 :(得分:2)
您可以将@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
}
选中此article,以获取有关使用 Spring Boot
进行测试的更多详细信息