第六节 SpringBoot使用单元测试

一、封装单元测试

      (1)SpringBoot的单元测试不依赖网络环境,可以直接在测试文件中指明当前激活的分支。

        先搭建了一个基本的SpringBoot环境。可以访问到当前项目中的任意Controller层接口。

        基本的GET、POST方法我已经封装,拿到后直接调用即可。

        

 

package com.zhoutianyu.learnspringboot;

import com.alibaba.fastjson.JSON;
import com.zhoutianyu.learnspringboot.test.Address;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.ActiveProfiles;
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.setup.MockMvcBuilders;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.context.WebApplicationContext;

import java.util.HashMap;
import java.util.Map;

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

@RunWith(SpringRunner.class)
@SpringBootTest
@ActiveProfiles("dev")
public class SpringBootJunitTest {

    private static final Logger LOGGER = LoggerFactory.getLogger(SpringBootJunitTest.class);

    @Autowired
    private WebApplicationContext wac;

    private MockMvc mockMvc;

    @Before
    public void setUp() {
        mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
    }


    private String get(String url, Map<String, String> params) throws Exception {
        final MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        map.setAll(params);
        return mockMvc.perform(
                MockMvcRequestBuilders.get(url)
                        .params(map)
                        .contentType(MediaType.APPLICATION_JSON_UTF8)
                        .accept(MediaType.APPLICATION_JSON_UTF8))
                .andExpect(status().isOk()).
                        andReturn().getResponse().getContentAsString();
    }

    private String post(String url, Object object) throws Exception {
        return mockMvc.perform(MockMvcRequestBuilders.post(url)
//                .header("wecSchoolId", 1).header("id", "1")
                .contentType(MediaType.APPLICATION_JSON_UTF8).content(JSON.toJSONString(object)))
                .andExpect(status().isOk())
                .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
                .andReturn().getResponse().getContentAsString();
    }
}

      (2)编写一个基础的Controller,来接收单元测试的请求。

        常见的URL请求分为GET请求与POST请求。

        GET请求传递参数的特点,参数直接写在请求URL中。

        POST请求传递的参数通常是一个实体,后端接收使用的是@RequsetBody接收。

package com.zhoutianyu.learnspringboot.test;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class JunitController {

    private static final Logger LOGGER = LoggerFactory.getLogger(JunitController.class);

    @GetMapping(value = "/get_test")
    public Address getRequest(Address address) {
        LOGGER.info("paramType is {}", address);
        return address;
    }

    @PostMapping(value = "/post_test")
    public Address postRequest(@RequestBody Address address) {
        LOGGER.info("paramType is {}", address);
        return address;
    }
}
package com.zhoutianyu.learnspringboot.test;

import lombok.Data;

@Data
public class Address {
    private String location;

    private Long number;
}

二、测试 

          在已经新建好的单元测试中,编写两个单元测试文件。调用封装好的 get 与 post 方法。启动单元测试。

    @Test
    public void testGet() throws Exception {
        String url = "/get_test";
        Map<String, String> map = new HashMap<>();
        map.put("location", "NanJing");
        map.put("number", "123456");
        String data = get(url, map);
        System.out.println("GET请求返回值是:" + data);
    }

    @Test
    public void testPost() throws Exception {
        String url = "/post_test";
        Address address = new Address();
        address.setLocation("BeiJing");
        address.setNumber(654321L);
        String data = post(url , address);
        System.out.println("POST请求返回值是:" + data);
    }

         因为我的全局响应已经统一,所以返回的参数可能与你们实际运行出来的有点区别。可参考:第五节 统一全局响应

         实际运行结果:

三、源码下载

        本章节项目源码:点我下载源代码

        目录贴:跟着大宇学SpringBoot-------目录帖

 

posted @ 2022-07-17 12:14  小大宇  阅读(272)  评论(0编辑  收藏  举报