RESTful接口单元测试

好的单元测试是代码中珍贵的宝石,无论在开发,对接测试,问题反查中都会体现它的价值。

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
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;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.WebApplicationContext;

import javax.annotation.Resource;
import java.util.Map;

/**
 *
 * Created by linjinzhi on 2019/1/8
 *
 * 单元测试父类.
 *
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public abstract class AbstractMockMvcTest {

    private static final Logger logger = LoggerFactory.getLogger(AbstractMockMvcTest.class);

    @Resource
    private WebApplicationContext webApplicationContext;

    private MockMvc mockMvc;

    private MockMvcTestConfig config;


    /**
     * 设置测试的一些参数.
     * @param mockMvcTestConfig 参数封装
     * @throws Exception 为空抛出异常
     */
    public void prepareTestConfig(MockMvcTestConfig mockMvcTestConfig) throws Exception {
        if(mockMvcTestConfig == null) {
            throw new Exception("test config is null");
        }

        this.config = mockMvcTestConfig;
    }

    @Before
    public void init() {
        mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
    }

    /**
     * 执行接口请求
     * @return MvcResult
     * @throws Exception 不支持的方法抛出异常
     */
    public MvcResult endpointTestTrigger() throws Exception {

        RequestMethod method = this.config.method;
        String endpoint = this.config.endpoint;
        Object parameter = this.config.parameter;
        Map<String, String> headers = this.config.headers;

        MockHttpServletRequestBuilder mockHttpServletRequestBuilder;

        HttpHeaders httpHeaders = new HttpHeaders();
        // 请求带有请求头
        if(headers != null && !headers.isEmpty()) {
            for(Map.Entry<String, String> entry : headers.entrySet()) {
                httpHeaders.add(entry.getKey(), entry.getValue());
            }
        }

        if(RequestMethod.GET.equals(method)) {
            mockHttpServletRequestBuilder = MockMvcRequestBuilders.get(endpoint).headers(httpHeaders);

        } else if(RequestMethod.POST.equals(method)) {
            String json = JSON.toJSONString(parameter, SerializerFeature.WriteMapNullValue);
            logger.info("post request body:{}", json);

            mockHttpServletRequestBuilder = MockMvcRequestBuilders.post(endpoint)
                    .contentType(MediaType.APPLICATION_JSON)
                    .content(json)
                    .headers(httpHeaders)
                    .accept(MediaType.APPLICATION_JSON);

        } else if(RequestMethod.PUT.equals(method)) {
            String json = JSON.toJSONString(parameter, SerializerFeature.WriteMapNullValue);
            logger.info("put request body:{}", json);

            mockHttpServletRequestBuilder = MockMvcRequestBuilders.put(endpoint)
                    .contentType(MediaType.APPLICATION_JSON)
                    .content(json)
                    .headers(httpHeaders)
                    .accept(MediaType.APPLICATION_JSON);

        } else if(RequestMethod.DELETE.equals(method)) {
            mockHttpServletRequestBuilder = MockMvcRequestBuilders.delete(endpoint).headers(httpHeaders);

        } else {
            throw new Exception("mock test not support http method: " + method.name());
        }

        MvcResult result = mockMvc.perform(mockHttpServletRequestBuilder)
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andDo(MockMvcResultHandlers.print())
                .andReturn();

        logger.info(result.getResponse().getContentAsString());
        return result;
    }


    /**
     * 测试相关参数封装
     */
    final class MockMvcTestConfig {
        /**
         * 请求接口的uri
         */
        String endpoint;
        /**
         * 请求参数体
         */
        Object parameter;
        /**
         * 接口支持http方法
         */
        RequestMethod method;

        /**
         * 请求头
         */
        Map<String, String> headers;
    }
}

具体单元测试继承上面的父类

/**
 * Created by linjinzhi on 2019/1/8
 */
public class SysLoginControllerTest extends AbstractMockMvcTest {


    @Test
    public void testPermission() throws Exception {
        Map<String, String> headers = new HashMap<>();
        headers.put(Constants.TERMINAL_ID, "chrome_v53.0.0");
        headers.put(Constants.TOKEN, "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJsb2dpbk5hbWUiOiJ0ZXN0MSIsInRpbWVzdGFtcCI6IjE1NTQ4ODgxNjk4ODkifQ.0cShvJ-Mq88Xs8EZLS9rOOroe8ui_poenG_yjtNnvkU");

        MockMvcTestConfig config = new MockMvcTestConfig();
        config.method = RequestMethod.GET;
        config.headers = headers;
        config.endpoint = "/test/test";

        prepareTestConfig(config);
        MvcResult result = endpointTestTrigger();
        System.out.println(result.getResponse().getContentAsString());
    }
}

转载于:https://my.oschina.net/ChiLin/blog/3062488

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值