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

相关推荐
麻芝汤圆22 分钟前
MapReduce 入门实战:WordCount 程序
大数据·前端·javascript·ajax·spark·mapreduce
juruiyuan1112 小时前
FFmpeg3.4 libavcodec协议框架增加新的decode协议
前端
熊大如如2 小时前
Java 反射
java·开发语言
Vone_662 小时前
node.js 邮箱验证服务器搭建
运维·服务器·node.js
Peter 谭3 小时前
React Hooks 实现原理深度解析:从基础到源码级理解
前端·javascript·react.js·前端框架·ecmascript
猿来入此小猿3 小时前
基于SSM实现的健身房系统功能实现十六
java·毕业设计·ssm·毕业源码·免费学习·猿来入此·健身平台
丢丢丢丢丢丢~3 小时前
apache2的默认html修改
linux·运维·服务器
wusam3 小时前
Linux系统管理与编程20:Apache
linux·运维·服务器·apache·shell编程
goTsHgo3 小时前
Spring Boot 自动装配原理详解
java·spring boot
ChironW3 小时前
Ubuntu 24.04 LTS系统上配置国内时间同步
linux·运维·服务器·ubuntu