SpringMVC测试
2016-03-29 10:50
429 查看
Spring提供了测试MVC的框架。
需要注解@WebAppConfiguration
注入WebApplicationContext
MockMvc初始化
执行Request请求
定义期望值
服务端测试(Server-Side Tests)
主要分为几个步骤:需要注解@WebAppConfiguration
注入WebApplicationContext
MockMvc初始化
执行Request请求
定义期望值
@RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration("src/main/webapp") @ContextConfiguration(locations = { "classpath:applicationContext.xml" }) public class BaseControllerTest { @Autowired private WebApplicationContext wac; private MockMvc mockMvc; @Before public void setup() { this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); //初始化具体某个controller // this.mockMvc = MockMvcBuilders.standaloneSetup(new CashierOrderController()).build(); } @Test public void testBase() throws Exception { MvcResult result = mockMvc.perform(MockMvcRequestBuilders.post("/api/") .accept(MediaType.APPLICATION_JSON) .param("foo", "bar")) .andExpect(status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn(); } }
客服端测试(Client-Side REST Tests)
目标是模拟一下响应response, 定义期望值public class SampleTests { private MockRestServiceServer mockServer; private RestTemplate restTemplate; @Before public void setup() { this.restTemplate = new RestTemplate(); this.mockServer = MockRestServiceServer.bindTo(this.restTemplate).ignoreExpectOrder().build(); } @Test public void performGet() throws Exception { String responseBody = "{\"name\" : \"Ludwig van Beethoven\", \"someDouble\" : \"1.6035\"}"; this.mockServer.expect(requestTo("/composers/42")).andExpect(method(HttpMethod.GET)) .andRespond(withSuccess(responseBody, MediaType.APPLICATION_JSON)); @SuppressWarnings("unused") Person ludwig = this.restTemplate.getForObject("/composers/{id}", Person.class, 42); // We are only validating the request. The response is mocked out. // hotel.getId() == 42 // hotel.getName().equals("Holiday Inn") this.mockServer.verify(); } }
相关文章推荐
- Android之使用Http协议实现文件上传功能
- 一个jar包里的网站
- 一个jar包里的网站之文件上传
- 一个jar包里的网站之返回对媒体类型
- mysql集群之MMM简单搭建
- Spring整合Quartz(JobDetailBean方式)
- Spring整合Quartz(JobDetailBean方式)
- 通晓网络测试常用命令
- Nodejs学习笔记之测试驱动
- 模拟Spring的简单实现
- spring+html5实现安全传输随机数字密码键盘
- Spring中属性注入详解
- springmvc 发送ajax出现中文乱码的解决方法汇总
- SpringMVC框架下JQuery传递并解析Json格式的数据是如何实现的
- struts2 spring整合fieldError问题
- 可以测试javascript运行效果的代码
- 使用php测试硬盘写入速度示例
- spring的jdbctemplate的crud的基类dao
- 读取spring配置文件的方法(spring读取资源文件)
- python 测试实现方法