spring boot 单元测试JUnit5使用MockMvc调用get请求,post请求,设置head请求头,解析返回值json和字符串

spring boot 单元测试JUnit5使用MockMvc调用get/post接口

源码地址:https://gitcode.net/qq_39339588/springboot.git

1. 先准备一份controller,一会儿供测试调用
package space.goldchen.springboot.test;

import org.springframework.web.bind.annotation.*;
import space.goldchen.springboot.entity.User;

/**
 * 使用mockMvc 调用get/post请求地址
 * @author chenzhao
 * @create 2023-05-29 16:33
 */
@RestController
@RequestMapping("/mvcTest")
public class MvcTestController {

    /**
     * get请求接口
     * @return
     */
    @GetMapping
    public String testGet(){
        return "get";
    }

    /**
     * post请求接口
     * @param user
     * @return
     */
    @PostMapping
    public User testPost(@RequestBody User user){
        return user;
    }

    /**
     * getById 请求
     * @param id
     * @return
     */
    @GetMapping("byId")
    public String testGetById(Integer id){
        return "get:"+id;
    }
}
2. MockMvc测试调用get请求接口

两个注解说明

@SpringBootTest // 加测试类上,标明是测试的类

@AutoConfigureMockMvc // 支持对MockMvc对象的注入和配置,测试get/post请求

测试get请求,传参json,添加请求头header,打印请求和响应

package space.goldchen.springboot.test;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
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.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
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 space.goldchen.springboot.entity.User;

import javax.annotation.Resource;

/**
 * 单元测试:测试调用controller接口请求
 *
 * @author chenzhao
 * @create 2023-05-29 16:37
 */
@SpringBootTest
//不用启动项目也可以调用MockMvc测试get/post请求
@AutoConfigureMockMvc
class MvcTestControllerTest {
    @Resource
    private MockMvc mockMvc;

    @Resource
    private ObjectMapper objectMapper;

    /**
     * 测试get请求,传参json,添加请求头header,打印请求和响应
     *
     * @throws Exception
     */
    @Test
    void testGet() throws Exception {
        mockMvc.perform(MockMvcRequestBuilders.get("/mvcTest")
                // 可以添加请求头
                .content("{\"username\":\"goldchen\",\"password\":\"123456\"}")
                .header("Authorization", "Bearer ..."))
                // .contentType(MediaType.APPLICATION_JSON)
                // .content("2"))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andDo(MockMvcResultHandlers.print())
                .andReturn();
    }
}
3. MockMvc测试调用get带参数请求接口

测试get请求,地址栏传参和param传参都行,添加请求头header,获取响应中的String字符串字段,打印请求响应结果

package space.goldchen.springboot.test;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
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.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
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 space.goldchen.springboot.entity.User;

import javax.annotation.Resource;

/**
 * 单元测试:测试调用controller接口请求
 *
 * @author chenzhao
 * @create 2023-05-29 16:37
 */
@SpringBootTest
//不用启动项目也可以调用MockMvc测试get/post请求
@AutoConfigureMockMvc
class MvcTestControllerTest {
    @Resource
    private MockMvc mockMvc;

    @Resource
    private ObjectMapper objectMapper;

    /**
     * 测试get请求,地址栏传参和param传参都行,添加请求头header,获取响应中的String字符串字段,打印请求响应结果
     *
     * @throws Exception
     */
    @Test
    void testGetById() throws Exception {
        int id = 1;
        mockMvc
                //地址栏传参和param传参都行
                .perform(MockMvcRequestBuilders.get("/mvcTest/byId?id=" + id)
                        .header("Authorization", "Bearer ...")
                        .param("id", "" + id)
                        .content("12")
                )
                .andExpect(MockMvcResultMatchers.status().isOk())
                // 返回结果中取值,并且去比较
                .andExpect(MockMvcResultMatchers.content().string("get:" + id))
                .andDo(MockMvcResultHandlers.print())
                .andReturn();
    }
}
4. MockMvc测试调用post请求接口

测试post请求,传参json,添加请求头header,获取响应中的json字段,打印请求响应结果

package space.goldchen.springboot.test;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
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.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
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 space.goldchen.springboot.entity.User;

import javax.annotation.Resource;

/**
 * 单元测试:测试调用controller接口请求
 *
 * @author chenzhao
 * @create 2023-05-29 16:37
 */
@SpringBootTest
//不用启动项目也可以调用MockMvc测试get/post请求
@AutoConfigureMockMvc
class MvcTestControllerTest {
    @Resource
    private MockMvc mockMvc;

    @Resource
    private ObjectMapper objectMapper;

    /**
     * 测试post请求,传参json,添加请求头header,获取响应中的json字段,打印请求响应结果
     *
     * @throws Exception
     */
    @Test
    void testPost() throws Exception {
        // json数据封装
        User user = new User();
        user.setUsername("goldchen");
        user.setPassword("123456");
        String contentString = objectMapper.writeValueAsString(user);
        // 接收处理结果
        MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.post("/mvcTest")
                .contentType(MediaType.APPLICATION_JSON)
                // 也可以手写json
                // .content("{\"username\":\"goldchen\",\"password\":\"123456\"}"))
                .content(contentString))
                .andExpect(MockMvcResultMatchers.status().isOk())
                // 可以取出 json的字段值
                .andExpect(MockMvcResultMatchers.jsonPath("$.username")
                        .value("goldchen"))
                .andDo(MockMvcResultHandlers.print()).andReturn();

        // 获取响应结果
        MockHttpServletResponse response = mvcResult.getResponse();
        // 打印作为字符串
        System.out.println(response.getContentAsString());
    }
}
  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
生成一个使用JUnit进行单元测试Spring boot 工程,可以按照以下步骤进行: 1. 使用Spring Initializr在线工具或者在Eclipse、IntelliJ IDEA等IDE中创建一个Spring boot项目,选择Web、JPA和MySQL等依赖。 2. 在pom.xml文件中添加JUnit和Mockito等测试依赖。 ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-core</artifactId> <scope>test</scope> </dependency> ``` 3. 创建一个测试类,使用JUnit和Mockito等工具进行测试。 ```java @RunWith(SpringRunner.class) @SpringBootTest public class UserServiceTest { @MockBean private UserRepository userRepository; @Autowired private UserService userService; @Test public void testGetUserById() { User user = new User(); user.setId(1L); user.setName("Test"); user.setAge(18); Mockito.when(userRepository.findById(1L)).thenReturn(Optional.of(user)); User result = userService.getUserById(1L); Assert.assertEquals(result.getName(), "Test"); Assert.assertEquals(result.getAge(), 18); } } ``` 在这个例子中,使用@RunWith和@SpringBootTest注解来配置测试环境,使用@MockBean注解来模拟依赖的UserRepository对象,使用@Autowired注解来注入需要测试的UserService对象,使用Mockito.when和Assert.assertEquals等方法来进行测试。 4. 运行测试用例,查看测试结果。 在Eclipse、IntelliJ IDEA等IDE中,可以右键点击测试类并选择Run As JUnit Test来运行测试用例。测试结果将会在控制台中输出。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Goldchenn

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值