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成功

相关推荐
D11_2 分钟前
【服务器】将本地项目部署到服务器
运维·服务器
TT哇4 分钟前
【多线程案例】:单例模式
java·单例模式·面试
EndingCoder11 分钟前
Electron 跨平台兼容性:处理 OS 差异
前端·javascript·electron·前端框架·node.js·chrome devtools
黄焖鸡能干四碗23 分钟前
智慧教育,智慧校园,智慧安防学校建设解决方案(PPT+WORD)
java·大数据·开发语言·数据库·人工智能
秋田君27 分钟前
Vue3+Node.js 实现大文件上传:断点续传、秒传、分片上传完整教程(含源码)
前端
爱隐身的官人27 分钟前
ctfshow - web - nodejs
前端·nodejs·ctf
zhong liu bin27 分钟前
Vue框架技术详解——项目驱动概念理解【前端】【Vue】
前端·javascript·vue.js·vscode·vue
敲上瘾27 分钟前
Docker 存储卷(Volume)核心概念、类型与操作指南
linux·服务器·数据库·docker·容器·架构
W-GEO27 分钟前
前端安全攻防:XSS, CSRF 等常见威胁的防范与检测指南
前端·安全·xss
2301_8035545230 分钟前
实习项目包装--HTTP 协议和 Web API
前端·网络协议·http