欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SpringMvc Controller单元测试

程序员文章站 2022-04-29 16:44:31
...

注意点

  • ContextConfiguration 读取配置文件:application.xml 与 spring-servlet.xml 2个文件都是需要进行读取的,而且其路径也不一样:
    @ContextConfiguration(locations = {"classpath:/applicationContext.xml", "file:src/main/webapp/WEB-INF/spring-servlet.xml"})
    

GET 与 POST请求例子

package com.shushangyunapi.web.controller;

import lombok.extern.slf4j.Slf4j;
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.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.WebApplicationContext;

import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

/**
 * @ Author     :SamLai
 * @ Date       :Created in 2019-07-17 14:20
 * @ Description:controller的测试
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:/applicationContext.xml", "file:src/main/webapp/WEB-INF/spring-servlet.xml"})
@Slf4j
@WebAppConfiguration
//配置事务的回滚,对数据库的增删改都会回滚,便于测试用例的循环利用
@Transactional
public class SimpleController {


    @Autowired
    private WebApplicationContext webApplicationContext;
    private MockMvc mockMvc;

    //方法执行前初始化数据
    @Before
    public void init() throws Exception {
        mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
    }


    /**
     * 第一种:
     * mockMvc get方法调用
     *
     * @throws Exception
     */
    @Test
    public void getTest() throws Exception {
        MockHttpServletRequestBuilder mockHttpServletRequestBuilder = MockMvcRequestBuilders.get("/policy/testprofile/value");
        mockHttpServletRequestBuilder.param("num", "1"); //要传入的参数
        ResultActions resultActions = mockMvc.perform(mockHttpServletRequestBuilder);
        resultActions.andExpect(status().isOk());
    }


    /**
     * 第二种:
     * mockMvc get方法调用 指定传输格式:MediaType.APPLICATION_JSON
     *
     * @throws Exception
     */
    @Test
    public void getTwoTest() throws Exception {
        String responseString = mockMvc.perform(MockMvcRequestBuilders.get("/policy/testprofile/value")
                .contentType(MediaType.APPLICATION_JSON)
                .param("num", "1")  //数据的格式   .contentType(MediaType.APPLICATION_FORM_URLENCODED)   数据的格式请求的url,请求的方法是get.contentType(MediaType.APPLICATION_FORM_URLENCODED)  //数据的格式 .param("pcode","root")         //添加参数
        ).andExpect(status().isOk()) //返回的状态是200
                .andDo(print())//打印出请求和相应的内容
                .andReturn().getResponse().getContentAsString();
        System.out.println("responseString  :  " + responseString);//在Controller 中加 @ResponseBody 可输出要返回的内容
    }


    /**
     * 第三种:
     * mockMvc post方法调用 指定传输格式:MediaType.APPLICATION_JSON
     *
     * @throws Exception
     */
    @Test
    public void postTest() throws Exception {
        String responseString = mockMvc.perform(MockMvcRequestBuilders.post("/policy/testTxAd")
                .contentType(MediaType.APPLICATION_JSON)
                .param("num", "1")  //数据的格式   .contentType(MediaType.APPLICATION_FORM_URLENCODED)   数据的格式请求的url,请求的方法是get.contentType(MediaType.APPLICATION_FORM_URLENCODED)  //数据的格式 .param("pcode","root")         //添加参数
        ).andExpect(status().isOk()) //返回的状态是200
                .andDo(print())//打印出请求和相应的内容
                .andReturn().getResponse().getContentAsString();
        System.out.println("responseString  :  " + responseString);//在Controller 中加 @ResponseBody 可输出要返回的内容
    }


}