• java springboot在测试类中构建虚拟MVC环境并发送请求


    好 上文java springboot在测试类中启动一个web环境我们在测试类中搭了一个web环境
    那么 下面就要想办法弄一个接口的测试
    这边 我们还是要在controller包下去创建一个 controller类 写一个访问接口
    这里 我创建一个 TestWeb.java
    在这里插入图片描述
    这里 我们编写代码如下

    package com.example.webdom.controller;
    
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    @RequestMapping("/TextWeb")
    public class TestWeb {
        @GetMapping
        public String getById(){
            System.out.println("getById is running .....");
            return "springboot";
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    写一个基本的 Controller 结构 放回一个字符串的接口

    然后 这里 我们需要搞清楚一点: 测试类请求接口 它对 MVC的调用 是真实的调用 还是 模拟的调用?
    它是模拟的调用啊

    我们测试类编写代码如下

    package com.example.webdom;
    
    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.request.MockHttpServletRequestBuilder;
    import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
    
    @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
    @AutoConfigureMockMvc
    public class WebDomApplicationTests {
    
        @Test
        void contextLoads(@Autowired MockMvc mvc) throws Exception {
            MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get("/TextWeb");
            mvc.perform(builder);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    这里 我们AutoConfigureMockMvc 表示开启 MVC的虚拟调用
    然后 我们测试方法中 条件装配一个参数 MockMvc 类型 MockMvc 要AutoConfigureMockMvc 开启虚拟调用后 才能使用
    然后 我们通过MockMvcRequestBuilders声明一个请求对象 get类型 地址 TextWeb
    然后 通过我们的参数 perform调用请求
    这里 我们需要抛出异常
    在这里插入图片描述
    然后 我们右键运行
    在这里插入图片描述
    我们从控制台上输出可以看出接口是被调用了
    在这里插入图片描述
    这是个虚拟环境发起的请求

  • 相关阅读:
    论文基本功——LaTeX:公式及其编号
    #QT(串口助手-实现)
    MySQL高级篇1
    Windows卸载ninja流程
    海康摄像机取流RTSP地址规则说明
    点赞、收藏必读文章--数据分析的多变量分析
    [二叉树&栈] 二叉树前序遍历和中序遍历的迭代写法
    Java项目之石头剪刀布
    十六、RabbitMQ快速入门
    47个Docker常见故障的原因和解决方式
  • 原文地址:https://blog.csdn.net/weixin_45966674/article/details/134531936