MockMvc单元测试

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_37782076/article/details/85090131

原始访问层代码

package com.example.demo.web;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author: 
 * @Date: 2018/12/19 09:33
 * @Description:
 */
@RestController
public class test1Controller {

    @RequestMapping("/testDemo")
    public String test1(){
        System.out.println("这是第一个测试");
        return "这是一个测试测试";
    }
}

单元测试案例(1)

package com.example.demo.web;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;


/**
 * @Author: 
 * @Date: 2018/12/19 09:44
 * @Description:
 */

@SpringBootTest()
@RunWith(SpringRunner.class)

public class test1ControllerTest {

    private MockMvc mvc;

    @Before
    public void setUp() {
        mvc = MockMvcBuilders.standaloneSetup(new test1Controller()).build();
    }

    @Test
    public void test1() throws Exception {
        mvc.perform(MockMvcRequestBuilders.get("/testDemo"))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andDo(MockMvcResultHandlers.print())
                .andReturn();
    }

}

运行结果(1)

 .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.1.RELEASE)

2018-12-19 10:36:01.912  INFO 2668 --- [           main] c.example.demo.web.test1ControllerTest   : Starting test1ControllerTest on M7072XFZ with PID 2668 (started by maokai in F:\learnProject\demo)
2018-12-19 10:36:01.914  INFO 2668 --- [           main] c.example.demo.web.test1ControllerTest   : No active profile set, falling back to default profiles: default
2018-12-19 10:36:03.285  INFO 2668 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2018-12-19 10:36:03.575  INFO 2668 --- [           main] c.example.demo.web.test1ControllerTest   : Started test1ControllerTest in 2.076 seconds (JVM running for 2.871)
2018-12-19 10:36:03.844  INFO 2668 --- [           main] o.s.mock.web.MockServletContext          : Initializing Spring TestDispatcherServlet ''
2018-12-19 10:36:03.845  INFO 2668 --- [           main] o.s.t.web.servlet.TestDispatcherServlet  : Initializing Servlet ''
2018-12-19 10:36:03.845  INFO 2668 --- [           main] o.s.t.web.servlet.TestDispatcherServlet  : Completed initialization in 0 ms
这是第一个测试

MockHttpServletRequest:
      HTTP Method = GET
      Request URI = /testDemo
       Parameters = {}
          Headers = {}
             Body = <no character encoding set>
    Session Attrs = {}

Handler:
             Type = com.example.demo.web.test1Controller
           Method = public java.lang.String com.example.demo.web.test1Controller.test1()

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = null

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 200
    Error message = null
          Headers = {Content-Type=[text/plain;charset=ISO-8859-1], Content-Length=[6]}
     Content type = text/plain;charset=ISO-8859-1
             Body = ??????
    Forwarded URL = null
   Redirected URL = null
          Cookies = []
2018-12-19 10:36:03.908  INFO 2668 --- [       Thread-2] o.s.s.concurrent.ThreadPoolTaskExecutor  : Shutting down ExecutorService 'applicationTaskExecutor'

单元测试案例(2)

package com.example.demo.web;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;

/**
 * @Author: 
 * @Date: 2018/12/19 09:44
 * @Description:
 */

@SpringBootTest()
@RunWith(SpringRunner.class)
@AutoConfigureMockMvc

public class test1ControllerTest1 {

    @Autowired
    private MockMvc mvc;

    @Test
    public void test1Controller() throws Exception {
        mvc.perform(MockMvcRequestBuilders.get("/testDemo"))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andDo(MockMvcResultHandlers.print())
                .andReturn();
    }
}

运行结果(2)

 .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.1.RELEASE)

2018-12-19 10:37:54.726  INFO 9248 --- [           main] c.example.demo.web.test1ControllerTest1  : Starting test1ControllerTest1 on M7072XFZ with PID 9248 (started by maokai in F:\learnProject\demo)
2018-12-19 10:37:54.727  INFO 9248 --- [           main] c.example.demo.web.test1ControllerTest1  : No active profile set, falling back to default profiles: default
2018-12-19 10:37:56.237  INFO 9248 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2018-12-19 10:37:56.479  INFO 9248 --- [           main] o.s.b.t.m.w.SpringBootMockServletContext : Initializing Spring TestDispatcherServlet ''
2018-12-19 10:37:56.479  INFO 9248 --- [           main] o.s.t.web.servlet.TestDispatcherServlet  : Initializing Servlet ''
2018-12-19 10:37:56.488  INFO 9248 --- [           main] o.s.t.web.servlet.TestDispatcherServlet  : Completed initialization in 9 ms
2018-12-19 10:37:56.506  INFO 9248 --- [           main] c.example.demo.web.test1ControllerTest1  : Started test1ControllerTest1 in 2.019 seconds (JVM running for 2.734)
这是第一个测试

MockHttpServletRequest:
      HTTP Method = GET
      Request URI = /testDemo
       Parameters = {}
          Headers = {}
             Body = null
    Session Attrs = {}

Handler:
             Type = com.example.demo.web.test1Controller
           Method = public java.lang.String com.example.demo.web.test1Controller.test1()

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = null

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 200
    Error message = null
          Headers = {Content-Type=[text/plain;charset=UTF-8], Content-Length=[18]}
     Content type = text/plain;charset=UTF-8
             Body = 这是一个测试
    Forwarded URL = null
   Redirected URL = null
          Cookies = []
2018-12-19 10:37:56.754  INFO 9248 --- [       Thread-3] o.s.s.concurrent.ThreadPoolTaskExecutor  : Shutting down ExecutorService 'applicationTaskExecutor'

方法一是用Mock去build一个测试类,然后再去请求,这样对于每一个测试类都需要重新写@before方法。而且从结果看其编码格式为ISO-8859-1 返回内容汉字都成了????。

方法二使用自动注入的形式,方法上自动注入 @AutoConfigureMockMvc   方法里面注入@Autowired 进行自动扫描,而且从结果看其编码格式为UTF-8 , 返回内容汉字不会乱码。

若需要更改乱码,需要设置接收数据类型如下

    @Test
    public void test1() throws Exception {
        mvc.perform(MockMvcRequestBuilders.get("/testDemo").accept(MediaType.APPLICATION_JSON_UTF8))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andDo(MockMvcResultHandlers.print())
                .andReturn();
    }

下面两个代码是将单元测试封装成一个接口,然后其他测试单元继承它之后就可以直接调用相应的请求方法。接口中用到了h2数据库,作为测试的基础数据。behind方法里面是调用登入接口,将返回的sessionId放入cookie中,作为调用其他接口的请求头里面的参数。若是接口没做登入权限判断这部分可以不要。header里面的User-Agent参数是因为请求对请求的用户代理方式(如pc/android/iOS等)做了拦截判断,若果没有这部分设置也可以不要,最后的AfterClass是删除h2数据库文件。若是你的测试直接连的其他数据库可以不需要,类上面压不需要注入@Sql语句

package com.comtop.map.store.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.comtop.map.store.common.RestObject;
import com.comtop.map.store.security.MD5;
import com.comtop.map.store.uom.bean.UserVO;
import org.hamcrest.Matchers;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.jdbc.Sql;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import javax.servlet.http.Cookie;
import java.io.File;

/**
 *
 * @author Vinicius Falcão
 *
 */
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
@Sql("/sql/testLogin.sql")
public abstract class AbstractControllerTest {

	@Autowired
	private MockMvc mockMvc;

	protected static final String account = "admin";

	protected static final String password = "123456";

	protected String sessionId = "";

	protected static final String userAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.80 Safari/537.36";

	@Before
	public void before() throws Exception {

		String url = "/login?account=" + account + "&password=" + MD5.getMD5Code(password);
		ResultActions resultActions = post(url).andExpect(MockMvcResultMatchers.status().isOk())
				.andExpect(MockMvcResultMatchers.jsonPath("$.data.account", Matchers.is(account)));
		String msg = resultActions.andReturn().getResponse().getContentAsString();
		RestObject<UserVO> restObject = JSON.parseObject(msg, new TypeReference<RestObject<UserVO>>(){});
		sessionId = restObject.getData().getSessionId();
		System.out.println(sessionId+"************************************");
	}

	protected ResultActions get(String url) throws Exception {
		return mockMvc.perform(MockMvcRequestBuilders.get(url)
				.cookie(new Cookie("JSESSIONID", sessionId)).header("User-Agent",userAgent));
	}

	protected ResultActions post(String url, String json) throws Exception {
		return mockMvc.perform(MockMvcRequestBuilders.post(url).contentType(MediaType.APPLICATION_JSON).content(json)
				.cookie(new Cookie("JSESSIONID", sessionId)).header("User-Agent",userAgent));
	}

	protected ResultActions post(String url) throws Exception {
		return mockMvc.perform(MockMvcRequestBuilders.post(url).contentType(MediaType.APPLICATION_JSON)
				.cookie(new Cookie("JSESSIONID", sessionId)).header("User-Agent",userAgent));
	}

	protected ResultActions delete(String url) throws Exception {
		return mockMvc.perform(MockMvcRequestBuilders.delete(url)
				.cookie(new Cookie("JSESSIONID", sessionId)).header("User-Agent",userAgent));

	}

	@AfterClass
	public static void delete() {
		String path = System.getProperty("user.home");

		File mvDBFile = new File(path + "/map-store.mv.db");
		if (mvDBFile.exists()) {
			mvDBFile.delete();
		}

		File traceDBFile = new File(path + "/map-store.trace.db");
		if (traceDBFile.exists()) {
			traceDBFile.delete();
		}
	}
}
package com.comtop.map.store.mobile.web.manage;

import com.comtop.map.store.mobile.bean.request.FeedbackAssignedParam;
import com.comtop.map.store.mobile.bean.request.FeedbackProcessingParam;
import com.comtop.map.store.utils.JsonUtils;
import com.comtop.map.store.web.AbstractControllerTest;
import org.hamcrest.Matchers;
import org.junit.Test;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;


/**
 * @Author: 
 * @Date: 2018/11/30 14:29
 * @Description:
 */
public class FeedBackManageControllerTest extends AbstractControllerTest {

    @Test
    public void fetchFeedBackPage() throws Exception{
        String url="/admin/feedback/fetchFeedBackPage?pageNum=0&pageSize=10&searchKeyword=&feedbackStatus=0";
        get(url).andExpect(MockMvcResultMatchers.status().isOk())
                .andDo(MockMvcResultHandlers.print())
                .andExpect(MockMvcResultMatchers.jsonPath("$.state", Matchers.is(0)));

    }

    @Test
    public void feedbackProcessing() throws Exception{
        FeedbackProcessingParam feedbackProcessingParam = new FeedbackProcessingParam();
        feedbackProcessingParam.setFeedbackId(497099590045712L);
        feedbackProcessingParam.setOperatingState("3");
        feedbackProcessingParam.setRemark3("这是关闭备注");
        String json= JsonUtils.toJSON(feedbackProcessingParam);
        String url="/admin/feedback/feedbackProcessing";

        post(url,json).andExpect(MockMvcResultMatchers.status().isOk())
                .andDo(MockMvcResultHandlers.print())
                .andExpect(MockMvcResultMatchers.jsonPath("$.state", Matchers.is(0)));
    }

    @Test
    public void feedbackAssigned() throws Exception{
        FeedbackAssignedParam feedbackAssignedParam = new FeedbackAssignedParam();
        feedbackAssignedParam.setContent("就是感觉你有问题,反馈一下");
        feedbackAssignedParam.setCreateDate("2018-11-29");
        feedbackAssignedParam.setDegreeOfDefect("1");
        feedbackAssignedParam.setFeedbackId(505611027492880L);
        feedbackAssignedParam.setFeedbackPriority("1");
        feedbackAssignedParam.setFeedbackType("新需求");
        feedbackAssignedParam.setOperatingState("1");
        feedbackAssignedParam.setFunctionModule("2");
        feedbackAssignedParam.setOperatingUserIds("492882952957968");
        feedbackAssignedParam.setRemark1("指派备注指派备注指派备注指派备注");
        feedbackAssignedParam.setUserName("周一");

        String json= JsonUtils.toJSON(feedbackAssignedParam);
        String url="/admin/feedback/feedbackAssigned";

        post(url,json).andExpect(MockMvcResultMatchers.status().isOk())
                .andDo(MockMvcResultHandlers.print())
                .andExpect(MockMvcResultMatchers.jsonPath("$.state", Matchers.is(0)));
    }

    @Test
    public void fetchFeedbackDetails() throws Exception {
        String url = "/admin/feedback/fetchFeedbackDetails?feedbackId=497818237030416";
        get(url).andExpect(MockMvcResultMatchers.status().isOk())
                .andDo(MockMvcResultHandlers.print())
                .andExpect(MockMvcResultMatchers.jsonPath("$.state", Matchers.is(0)))
                .andExpect(MockMvcResultMatchers.jsonPath("$.data.content", Matchers.is("经常闪退")))
                .andExpect(MockMvcResultMatchers.jsonPath("$.data.createDate", Matchers.is("2018-11-07")))
                .andExpect(MockMvcResultMatchers.jsonPath("$.data.equipmentModel", Matchers.is("000001c4c309b410")))
                .andExpect(MockMvcResultMatchers.jsonPath("$.data.feedbackId", Matchers.is("497818237030416")))
                .andExpect(MockMvcResultMatchers.jsonPath("$.data.feedbackType", Matchers.is("功能性")))
                .andExpect(MockMvcResultMatchers.jsonPath("$.data.feedbackTypeId", Matchers.is("487113710800912")))
                .andExpect(MockMvcResultMatchers.jsonPath("$.data.phone", Matchers.is("18566292141")))
                .andExpect(MockMvcResultMatchers.jsonPath("$.data.userName", Matchers.is("系统管理员")));
    }

    @Test
    public void exportExcel() throws Exception{
        String url = "/admin/feedback/exportExcel?searchKeyword=&feedbackStatus=0&flag=0";
        get(url).andExpect(MockMvcResultMatchers.status().isOk())
                .andDo(MockMvcResultHandlers.print());
    }
}

猜你喜欢

转载自blog.csdn.net/qq_37782076/article/details/85090131