springboot-5-springboot使用MockMvc测试接口

首先编写一个controller

package com.example.lchtest.springbootdemo1.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class GetController {
    @RequestMapping("/test/getName")
    @ResponseBody
    public  String test(){
        System.out.println("********* 请求处理中 *********");
        return "hello";
    }
}

MockMvc的作用: 模拟接口请求,等同于一个http客户端
(1) 测试类上面加上@AutoConfigureMockMvc注解
(2) MockMvc常用方法
perform()方法 : 执行一个RequestBuilder请求
andExpect: 添加ResultMatcher-> MockMvcResultMatchers验证规则
andReturn 返回相应的MvcResult

package com.example.lchtest.springbootdemo1;

import org.junit.jupiter.api.Test;
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.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.MockMvcResultMatchers;

/**
 * springboot测试 @SpringBootTest注解后面要加上主启动类,否则会报错
 */
@AutoConfigureMockMvc
@SpringBootTest(classes={App.class})
public class MockMvcTest {

    /**
     * mockMvc等同于一个http客户端
     */
    @Autowired
    private MockMvc mockMvc;

    @Test
    public void  apiTest() throws Exception {
        MvcResult mvcResult =  mockMvc.perform(MockMvcRequestBuilders.get("/test/getName"))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andReturn();
        int status = mvcResult.getResponse().getStatus();
        System.out.println(status);
    }
}

测试结果
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值