简体   繁体   English

如何使用springboot为rest控制器、服务和dao层编写junit测试用例?

[英]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 ?如何为RestControllerServiceDAO 层编写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

Complete source code 完整的源代码

    @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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM