如何使用springboot编写rest controller、service和dao层的junit

如何为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方法?


饮歌长啸
浏览 99回答 1
1回答

炎炎设计

您可以使用服务层模拟DAO 层@RunWith(MockitoJUnitRunner.class)组件来进行单元测试。你不需要它。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         }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java