ssm框架中Controller层的junit测试_我改

Controller测试和一般其他层的junit测试可以共用一个BaseTest

一、BaseTest如下

 1 @RunWith(SpringJUnit4ClassRunner.class)
 2 @WebAppConfiguration("src/main/resouces")//指定要加载的测试用的配置文件的根目录,其实就是下面的classpath路径
 3 @ContextConfiguration(locations={"classpath:Spring-config.xml","classpath:Spring-servlet.xml"})
 4 public class BaseTest{
 5     protected Logger log = LoggerFactory.getLogger(getClass());
 6     
 7     @Test
 8     public void test(){
 9         System.out.pringln(|"aaa");
10     }
11 }

上面这个基类要注意两点:

1、

@WebAppConfiguration("src/main/resouces")

用来指定要加载的测试用的配置文件的根目录就是我们的正常开发目录,而不是maven项目自动生成的 /src/test/resouces 目录

2、

@ContextConfiguration(locations={"classpath:Spring-config.xml","classpath:Spring-servlet.xml"})

其中 

"classpath:Spring-config.xml" 是后端 spring的配置文件,当然其中还可以引用包括各种其他配置文件,如dataSource.xml,mybatis.xml等
"classpath:Spring-servlet.xml" 是前端控制器的配置文件,主要是前台展示的各种资源向后台请求的配置,包括各种静态资源的请求,拦截等配置(如果不测试Controller层,貌似这个前端的配置文件可以不引入)

二、Controller层的测试如下

 1 public class  UserControllerTest extends BaseTest
 2 {
 3 
 4    @Autowired
 5    protected UserController userController; //注入我们要测试的某个Controller的bean
 6    
 7    protected MockMvc mockMvc; //这个是Controller测试必须的
 8 
 9    @Before()  //这个方法在每个方法执行之前都会执行一遍
10    public void setup() 
11    {
12           //括号里面填写我们要测试的 Controller的 bean名称,就是前面注入的成员变量
13        mockMvc = MockMvcBuilders.webAppContextSetup(userController).build();  //初始化MockMvc对象
14    }
15 
16    @Test
17    public void myTest() throws Exception 
18    {
19        String responseString = mockMvc.perform
20            (
21                get("/user/showUser1")          //模拟请求的url,请求的方法是get
22                //get("/user/showUser2")          //请求的url,请求的方法是get
23                .contentType(MediaType.APPLICATION_FORM_URLENCODED)//数据的格式
24                .param("id","1")   //添加请求参数(可以添加多个) 这里是要查询id为1的用户的信息
25                //.param("id","3")   //添加参数(可以添加多个)
26            )
27            .andExpect(status().isOk())    //期望返回的状态是200
28            .andDo(print())         //控制台打印出请求和相应的内容
29            .andReturn().getResponse().getContentAsString();   //将相应的Controller方法返回的数据转换为字符串
30        System.out.println("-----返回的json = " + responseString);//控制台打印返回的内容
31    }
32 
33 }
原文地址:https://www.cnblogs.com/libin6505/p/8385210.html