1.上一篇博客是初步創建了springboot。接下來咱們編寫測試用例來測試springboot的運行結果。java
2.在 test/java 目錄下創建一個測試用例類web
package com.myspringboot.study; import com.myspringboot.web.HelloController; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import static org.hamcrest.core.IsEqual.equalTo; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @RunWith(SpringRunner.class) @SpringBootTest(classes=HelloController.class) @AutoConfigureMockMvc public class StudyApplicationTests { @Test public void contextLoads() { } @Autowired private MockMvc mvc; @Test public void getHello() throws Exception { mvc.perform(MockMvcRequestBuilders.get("/hello").accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().string(equalTo("hello world"))); } }
上面的SpringBootTest(classes=)指向的是測試的controllerspring
而下面的getHello方法,是經過模擬請求 /hello 地址,判斷他的狀態和他的返回結果。springboot
注意事項 :mvc
創建測試用例的SpringBootTest(classes)所指向的類,他的目錄必定要在最外面,如目錄是在com.study下,若是你想測試com目錄下的類,是測試不了的,由於springboot的規則是掃描SpringBootTest(classes)所在目錄及子目錄的類,這點注意一下。測試