網上基本都是參考官方的使用方式,使用了import static,我的感受這種方式特別很差,代碼提示性不友好。因此在此進行說明,也方便本身之後使用。java
1. 引入spring-test相關jar包,springboot只需引入spring-boot-starter-test便可web
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency>
2. 寫好controller,開始寫test類spring
import org.front.server.Application; import org.front.server.web.control.TestController; import org.hamcrest.Matchers; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultHandlers; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; //網上不少會在這裏使用import static,主要導入的是MockMvcRequestBuilders,MockMvcResultMatchers,Matchers這三個類中的方法。
/**
* @author zz
* @date 2017年7月4日
*
*/
@RunWith(SpringJUnit4ClassRunner.class)
//@SpringApplicationConfiguration(classes = MockServletContext.class)//這個測試單個controller,不建議使用
@SpringApplicationConfiguration(classes = Application.class)//這裏的Application是springboot的啓動類名。
@WebAppConfiguration
public class ApplicationTests {
@Autowired
private WebApplicationContext context;
private MockMvc mvc;
@Before
public void setUp() throws Exception {
// mvc = MockMvcBuilders.standaloneSetup(new TestController()).build();
mvc = MockMvcBuilders.webAppContextSetup(context).build();//建議使用這種
}
@Test
public void test1() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/data/getMarkers")
.contentType(MediaType.APPLICATION_JSON_UTF8)
.param("lat", "123.123").param("lon", "456.456")
.accept(MediaType.APPLICATION_JSON))
.andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print())
.andExpect(MockMvcResultMatchers.content().string(Matchers.containsString("SUCCESS")));
}
}
相信這樣,基本開發過javaweb的就都能看懂了。經過方法的字面意思應該都能看懂方法含義,若是實在不懂請看源碼或者官方API。springboot