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

相关推荐
一个水瓶座程序猿.几秒前
ES6数组的`flat()`和`flatMap()`函数用法
前端·ecmascript·es6
能工智人小辰6 分钟前
二刷 苍穹外卖day10(含bug修改)
java·开发语言
DKPT6 分钟前
Java设计模式之结构型模式(外观模式)介绍与说明
java·开发语言·笔记·学习·设计模式
缘来是庄9 分钟前
设计模式之外观模式
java·设计模式·外观模式
袁煦丞16 分钟前
AI直接出答案!Perplexica开源搜索引擎:cpolar内网穿透实验室第534个成功挑战
前端·程序员·远程工作
Hilaku18 分钟前
用“人话”讲明白10个最常用的正则表达式
前端·javascript·正则表达式
木叶丸27 分钟前
跨平台方案该如何选择?
android·前端·ios
LL.。30 分钟前
同步回调和异步回调
开发语言·前端·javascript
网络点点滴34 分钟前
Vue如何处理数据、v-HTML的使用及总结
前端·vue.js·html
运维咖啡吧36 分钟前
周一才上线的网站,单单今天已经超过1000访问了
前端·程序员·ai编程