博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
spring test---測试SpringMvc初识
阅读量:4502 次
发布时间:2019-06-08

本文共 2075 字,大约阅读时间需要 6 分钟。

如今越来越多人使用SpringMvc来开发系统,在开发中可定须要对后台url地址请求測试,而且返回预期的结果!

Spring提供的測试类MockMvc来进行url地址请求測试,使用方方式:

package com.cml.controller;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
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.ResultActions;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration

@ContextConfiguration(locations = { "classpath:applicationContext.xml",

"classpath:mvc.xml" })
public class ExampleTests
{
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
@Before
public void setup()
{
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
}
@Test
public void getAccount() throws Exception
{
System.out.println("返回json。

。。。。

。。。。

。。");

ResultActions actions = this.mockMvc.perform(
get("/ll.mvc").param("name", "DDDDDDD").accept(
MediaType.APPLICATION_JSON)).andExpect(status().isOk());
System.out.println("測试成功");
}
}

解释:

@WebAppConfiguration 声明为web环境測试

@ContextConfiguration(locations = { "classpath:applicationContext.xml",

"classpath:mvc.xml" }) spring 和mvc的配置文件位置

@RunWith(SpringJUnit4ClassRunner.class)使用spring測试

转载于:https://www.cnblogs.com/liguangsunls/p/7246202.html

你可能感兴趣的文章
20180911-Java实例01
查看>>
Javascript Event
查看>>
sql语句 字段的赋值
查看>>
解决IOS safari下滑动的“橡皮筋”效果
查看>>
asp.net 得到一个文件夹下的所有文件夹及子文件夹名,得到所有文件名,文件大小,文件夹大小...
查看>>
从keystore(jks)文件中提取私钥
查看>>
调整数组顺序使奇数位于偶数前面
查看>>
css3的3D和2D
查看>>
简单的响应式布局的实现
查看>>
jQuery(属性操作)
查看>>
Python之路【第九篇】:Python面向对象
查看>>
background和background-image一点小区别
查看>>
ASCII码对照表
查看>>
HackerRank "Training the army" - Max Flow
查看>>
jquery next()方法
查看>>
深入剖析js命名空间函数namespace
查看>>
SQLHelper
查看>>
用标准Struts2+mvc写的用户管理
查看>>
Cocos2d-x 3.0 编译出错 解决 error: expected ';' at end of member declaration
查看>>
Ubuntu12.04下载Repo
查看>>