最近在使用一个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

只要在某一个或者某两个的jar包这种核心的jar包,其余的核心的jar包就会自动引入过来,在maven项目中引入jar包的时候不少事jar自己的依赖就会自动引过来,因为我遇到的版本的问题,就须要手动删除或者增长本身须要的jar包的依赖,而后才能解决,如图所示中我须要的一些基本jar就能够直接使用spring-security-config自动引过来就好了。post