springboot使用MockMvc进行单元测试

在我们写后台接口的时候,提供除去的接口往往容易出现很多小问题,从而引起和前端调用者的日常开撕。进而不断调整接口,降低了开发效率,这时候我们就需要使用到单元测试了,虽然增加了一点点的工作量,但是保证了接口的稳定性,也不需要和其他调用者进行不必要的口舌之争。

    以下是在springboot中使用MockMvc进行接口自测,使用方法具体如下:

1.添加所需要的依赖:

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-test</artifactId>
   <scope>test</scope>
</dependency>

 

2.在test文件夹下编写一个测试类Application1TestMVC,以下是类的具体代码:

package com.springbootmybatis;

import com.alibaba.fastjson.JSON;
import com.springbootmybatis.empty.option.UserOption;
import org.junit.Before;
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.http.MediaType;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

/**
 * Created by xkx on 2020/2/6.
 */
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc // 注入MockMvc
@WebAppConfiguration
public class Application1TestMVC {

    private MockMvc mvc;

    @Autowired
    private WebApplicationContext context;

    @Before
    public void setUp() {
        mvc = MockMvcBuilders.webAppContextSetup(context).build();
    }
    /**
     *
     * @throws Exception
     * @功能描述  通过链接传值 , 接受string 返回值
     */
    @Test
    public void testString() throws Exception {
        //准备请求url  不用带ip、端口、项目名称等 直接写接口的映射地址就可以了
        String url = "/user/db2/auto/1";

        /* 构建request 发送请求GET请求
         * MockMvcRequestBuilders 中有很多 请求方式。像get、post、put、delete等等
         */
        MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.get(url)
                .accept(MediaType.APPLICATION_JSON)) // 断言返回结果是json
                .andReturn();// 得到返回结果

        MockHttpServletResponse response = mvcResult.getResponse();
        //拿到请求返回码
        int status = response.getStatus();
        //拿到结果
        String contentAsString = response.getContentAsString();

        System.err.println(status);
        System.err.println(contentAsString);
    }

    /**
     *
     * @throws Exception
     * @功能描述  传递post请求和 bean类型对象 ,接受 返回值
     */
    @Test
    public void postTest() throws Exception {
        // uri
        String uri = "/user/db2/save/user-option";

        UserOption userOption = new UserOption();
        userOption.setUserName("name3testsave");
        userOption.setUserPassword("pwd3testsave");

        MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.post(uri)
                .contentType(MediaType.APPLICATION_JSON_UTF8)
                .content(JSON.toJSONString(userOption))
                .accept(MediaType.APPLICATION_JSON)) // 断言返回结果是json
                .andReturn();// 得到返回结果

        MockHttpServletResponse response = mvcResult.getResponse();
        //拿到请求返回码
        int status = response.getStatus();
        //拿到结果
        String contentAsString = response.getContentAsString();

        System.err.println(status);
        System.err.println(contentAsString);
    }

}

其中写了get和post单元测试调用接口的示例 testString()是get请求,postTest是post请求,需要特别注意@Before注解下的setUp()方法不可省略。

 

然后我们在依次测试写好的测试用例即可(结果如下):

post请求单元测试结果:

 

get请求单元测试结果:

以上就是本篇博客的全部内容,如有错误欢迎指正。另外附上该项目(该项目使用springboot整合了mybatis-plus,redis,swagger2,页面跳转jsp,实现异常的统一处理,druid整合多数据源切换【基于注解】)的地址 :https://github.com/xkx0912/springboot-study-master

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值