spring-mvc/springboot使用MockMvc對controller進行測試

這篇文章主要介紹了spring-mvc/springboot使用MockMvc對controller進行測試,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

網上基本都是參考官方的使用方式,使用了import static,個人感覺這種方式特別不好,代碼提示性不友好。所以在此進行說明,也方便自己以後使用。

1. 引入spring-test相關jar包,springboot只需引入spring-boot-starter-test即可

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
    </dependency>

2. 寫好controller,開始寫test類

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。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持神馬文庫。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章