如何使用springboot编写用于剩余控制器,服务和dao层的junit测试用例? [英] How to write junit test cases for rest controller, service and dao layer using springboot?

查看:143
本文介绍了如何使用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

这篇关于如何使用springboot编写用于剩余控制器,服务和dao层的junit测试用例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆