SpringBoot测试类启动web环境

1.坐标修改

XML 复制代码
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

2.测试类测试

说明:@SpringBootTest()中的webEnvironment值的说明;

2.1不启动

说明:默认不启动,如下图所示。@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE)。

java 复制代码
package com.forever;

import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE)
public class WebTest {
    @Test
    void test(){

    }

}

2.2默认端口

说明:@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)

java 复制代码
package com.forever;

import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class WebTest {
    @Test
    void test(){

    }

}

2.3 随机端口

说明:随机端口,@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)。

java 复制代码
package com.forever;

import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class WebTest {
    @Test
    void test(){

    }

}

3.发送虚拟请求

3.1@AutoConfigureMockMvc

说明:开启虚拟mvc调用。

java 复制代码
package com.forever;

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.RequestBuilder;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
//开启虚拟mvc调用
@AutoConfigureMockMvc
public class WebTest {

    @Test
    //形参写入或者上方写@Autowired;为方法注入资源。
    void testWeb(@Autowired MockMvc mockMvc) throws Exception {
        //发请求http://....../users;下面就是模拟的一个http请求,访问的是users
        MockHttpServletRequestBuilder builder= MockMvcRequestBuilders.get("/users");
        //执行对应的请求。
        mockMvc.perform(builder);

    }


}

3.2成功

相关推荐
武子康1 小时前
Java-80 深入浅出 RPC Dubbo 动态服务降级:从雪崩防护到配置中心秒级生效
java·分布式·后端·spring·微服务·rpc·dubbo
caolib1 小时前
无需云服务器的内网穿透方案 -- cloudflare tunnel
运维·服务器·内网穿透·tunnel·cloudflared
灵感__idea2 小时前
JavaScript高级程序设计(第5版):好的编程就是掌控感
前端·javascript·程序员
誰能久伴不乏2 小时前
Linux系统调用概述与实现:深入浅出的解析
linux·运维·服务器
程序员学习随笔2 小时前
Linux进程深度解析(2):fork/exec写时拷贝性能优化与exit资源回收机制(进程创建和销毁)
linux·运维·服务器
-SGlow-3 小时前
MySQL相关概念和易错知识点(2)(表结构的操作、数据类型、约束)
linux·运维·服务器·数据库·mysql
烛阴3 小时前
Mix
前端·webgl
代码续发3 小时前
前端组件梳理
前端
代码改变世界ctw3 小时前
Linux内核设计与实现 - 第14章 块I/O层
linux·运维·服务器
Dreams_l4 小时前
网络编程2(应用层协议,传输层协议)
运维·服务器·网络