最近在使用一個spring自己封裝的MockMvc自己封裝的測試框架來測試我寫的接口,Mockmvc的最大好處就是不可啟動服務器來測試controller程序,下面看一下程序
用到這三個注解
- RunWith(SpringJUnit4ClassRunner.class): 使用Spring Test組件進行單元測試;
- WebAppConfiguration: 使用這個Annotate會在跑單元測試的時候真實的啟一個web服務,然后開始調用Controller的Rest API,待單元測試跑完之后再將web服務停掉;
- ContextConfiguration: 指定Bean的配置文件信息,可以有多種方式,這個例子使用的是文件路徑形式,如果有多個配置文件,可以將括號中的信息配置為一個字符串數組來表示;
測試代碼如下:
| 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");// 健康卡應用業務類別代碼 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 ""; } |
代碼一切都沒問題,問題出來了,就是這個MockMvc對spring版本有要求,而在項目使用的框架是低版本的,剛開始在pom.xml里面把我springde jar包換成4.0以上的。但是呢。項目就是會報各種各樣jar版本不兼容的問題,比如這個
就是高版本里面spring沒有集成json的jar包(我用的阿里的),后來解決了,又來了一個log4j問題,總之各種高低版本不能互相兼容,然后我就進入pom文件中的jar進入看了一下,

只要在某一個或者某兩個的jar包這種核心的jar包,其他的核心的jar包就會自動引入過來,在maven項目中引入jar包的時候很多事jar本身的依賴就會自動引過來,由於我遇到的版本的問題,就需要手動刪除或者增加自己需要的jar包的依賴,然后才能解決,如圖所示中我需要的一些基本jar就可以直接使用spring-security-config自動引過來就行了。