龙空技术网

[易学springboot]对controller层进行单元测试

IT技术圈 914

前言:

眼前咱们对“springboot自动生成controller”大约比较关怀,各位老铁们都想要学习一些“springboot自动生成controller”的相关知识。那么小编也在网上汇集了一些有关“springboot自动生成controller””的相关资讯,希望同学们能喜欢,姐妹们一起来了解一下吧!

在springboot中进行单元测试,大家已经非常熟悉。我们通常测试的是service层和dao层。

对controller层的直接测试可能进行的较少。

下面介绍一下在SpringBoot中进行Controller层的Rest请求测试的方法。

还是使用我之前的一个rest请求

第一种方法:

@RunWith(SpringRunner.class)// 随机创建出一个端口测试@SpringBootTest(classes = DemoApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)public class HelloControllerTest {  @Autowired private TestRestTemplate restTemplate;  @Test public void sayHello() throws Exception { ResponseEntity<String> response = this.restTemplate.getForEntity("/hello", String.class); System.out.println(String.format("测试结果为:%s", response.getBody())); }}
第二种方法:
@RunWith(SpringRunner.class)@WebMvcTest(controllers = {HelloController.class})public class HelloControllerTest2 { @Autowired private MockMvc mockMvc; @MockBean public Uncle uncle; @Test public void sayHello() throws Exception { ResultActions perform = mockMvc.perform(MockMvcRequestBuilders.get("/hello")); // 打印下结果看看 System.out.println(perform.andReturn().getResponse().getContentAsString()); perform.andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.content().string("content name is uncley and age is 40")); }}

注意,有一个mockBean。其实我根本用不到这个。但是因为我测试的Controller中有这个依赖。

这种方式只测试controller,controller里面的一些依赖,需要你自己去mock。所以有点麻烦

@WebMvcTest 不能同时使用@SpringBootTest,所以不会加载整个spring容器。

第三种方式:

因为第二种方法有点不爽,看了下源码,有这么一句

说如果你想加载整个容器,那就别用@WebMvcTest,使用@SpringBootTest和@AutoConfigureMockMvc组合

那么,来吧,问题迎刃而解

@RunWith(SpringRunner.class)@SpringBootTest(classes = DemoApplication.class)@AutoConfigureMockMvcpublic class HelloControllerTest3 { @Autowired private MockMvc mockMvc; @Test public void sayHello() throws Exception { ResultActions perform = mockMvc.perform(MockMvcRequestBuilders.get("/hello")); // 打印下结果看看 System.out.println(perform.andReturn().getResponse().getContentAsString()); perform.andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.content().string("content name is uncley and age is 40")); }}

总结:

随着springboot的发展,单元测试是越来越简单了

标签: #springboot自动生成controller