最近在使用一個spring本身封裝的MockMvc本身封裝的測試框架來測試我寫的接口,Mockmvc的最大好處就是不可啓動服務器來測試controller程序,下面看一下程序web
用到這三個註解spring
- RunWith(SpringJUnit4ClassRunner.class): 使用Spring Test組件進行單元測試;
- WebAppConfiguration: 使用這個Annotate會在跑單元測試的時候真實的啓一個web服務,而後開始調用Controller的Rest API,待單元測試跑完以後再將web服務停掉;
- ContextConfiguration: 指定Bean的配置文件信息,能夠有多種方式,這個例子使用的是文件路徑形式,若是有多個配置文件,能夠將括號中的信息配置爲一個字符串數組來表示;
測試代碼以下:json
import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; 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.MvcResult; import org.springframework.test.web.servlet.ResultActions; 數組 @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"classpath*:/spring-servlet.xml","classpath*:/spring-config.xml"}) @WebAppConfiguration public class BaseJunitTest { protected MockMvc mockMvc; protected ResultActions resultActions; protected MvcResult mvcResult ; }服務器 @Test public void sendJMJKK0104Test() { Map map = new HashedMap(); map.put("app_userID", "254852"); map.put("virtual_card_id", "502C3CA91F65706E6BCDC9941860E980D38C53E34475F4D0CC47122EB3239252"); map.put("qr_code_type", "1"); // 二維碼類型 map.put("qr_code_load_type", "1"); // 二維碼獲取方式 map.put("tranCode", "01");// 健康卡應用業務類別代碼mvc sendPostMvc("訪問的路徑", map); } private String sendPostMvc(String path,Map params) { try {
ResultActions result = mockMvc.perform(post(path) .contentType(MediaType.APPLICATION_JSON)//驗證響應contentType .content(JSONObject.toJSONString(params)));//傳遞json格式參數 result.andDo(print()); result.andExpect(MockMvcResultMatchers.status().isOk()); String responseString = result.andReturn().getResponse().getContentAsString(); System.out.println("=====客戶端得到反饋數據:" + responseString); return responseString; } catch (Exception e) { e.printStackTrace(); } return ""; }app |
代碼一切都沒問題,問題出來了,就是這個MockMvc對spring版本有要求,而在項目使用的框架是低版本的,剛開始在pom.xml裏面把我springde jar包換成4.0以上的。可是呢。項目就是會報各類各樣jar版本不兼容的問題,好比這個
框架
就是高版本里面spring沒有集成json的jar包(我用的阿里的),後來解決了,又來了一個log4j問題,總之各類高低版本不能互相兼容,而後我就進入pom文件中的jar進入看了一下,maven
![](http://static.javashuo.com/static/loading.gif)
只要在某一個或者某兩個的jar包這種核心的jar包,其餘的核心的jar包就會自動引入過來,在maven項目中引入jar包的時候不少事jar自己的依賴就會自動引過來,因爲我遇到的版本的問題,就須要手動刪除或者增長本身須要的jar包的依賴,而後才能解決,如圖所示中我須要的一些基本jar就能夠直接使用spring-security-config自動引過來就好了。post