在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的發展,單元測試是越來越簡單了