如何使用springboot编写用于剩余控制器,服务和dao层的junit测试用例?

问题描述:

如何为 RestController Service DAO层编写 JUnit 测试用例?

How to write JUnit Test cases for RestController, Service and DAO layer?

我尝试了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 方法?

How can I verify the CRUD methods inside the rest controller and other layers ?

您可以将@RunWith(MockitoJUnitRunner.class)用于模拟 DAO层组件的服务层进行单元测试.您不需要SpringRunner.class.

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);
        }
    }

您可以使用@DataJpaTest进行集成测试 您的 DAO层

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     
    }

检查此文章,以获取有关使用 Spring Boot进行测试的更多详细信息

Check this article for getting more details about testing with Spring Boot