SpringBoot测试——高级配置

在这里插入图片描述

个人简介:Java领域新星创作者;阿里云技术博主、星级博主、专家博主;正在Java学习的路上摸爬滚打,记录学习的过程~
个人主页:.29.的博客
学习社区:进去逛一逛~

在这里插入图片描述



一、SpringBoot加载测试专用属性

加载测试范围的临时属性,应用于小范围测试环境


1.@SpringBootTest注解的properties参数


  • 在启动测试环境时,可以通过properties参数设置测试环境专用的属性
/**
 * @author .29.
 * @create 2023-04-01 20:28
 */
//properties属性,可以为当前测试用添加临时的属性配置
@SpringBootTest(properties = "test.prop=testValueByProperties")
public class PropertiesAndArgsTest {

    @Value("${test.prop}")
    private String msg;

    @Test
    public void testProperties(){
        System.out.println(msg);
    }
}

在这里插入图片描述


  • 对应的application.yml配置文件内容:
test:
  prop: 

优势:比多环境开发中的测试环境影响范围小,仅在当前测试类有效。



2.@SpringBootTest注解的args参数


  • 在启动测试环境时,可以通过args参数设置测试环境专用的传入属性
/**
 * @author .29.
 * @create 2023-04-01 20:28
 */

//args属性,可以为当前测试用例添加临时的命令行参数
@SpringBootTest(args = {"--test.prop=testValueByArgs"})
public class PropertiesAndArgsTest {

    @Value("${test.prop}")
    private String msg;

    @Test
    public void testProperties(){
        System.out.println(msg);
    }
}

在这里插入图片描述


  • 对应的application.yml配置文件内容:
test:
  prop: 




二、SpringBoot加载测试专用配置

加载测试范围配置,应用于小范围测试环境


  • 专用的配置:
/**
 * @author .29.
 * @create 2023-04-01 21:27
 */
//专用的配置
@Configuration
public class MsgConfig {
    @Bean
    public String msg(){
        return "test @Import get msg";
    }
}


  • 使用@Import注解,可以加载当前测试类专用的配置:
/**
 * @author .29.
 * @create 2023-04-01 21:30
 */
@SpringBootTest
@Import(MsgConfig.class)
public class ConfigurationTest {
    @Autowired
    private String msg;

    @Test
    public void testConfiguration(){
        System.out.println(msg);
    }
}

成功加载到专用配置中的内容:

在这里插入图片描述




三、SpringBoot 模拟测试Web环境

Web环境模拟测试

  1. 设置测试端口
  2. 模拟测试启动
  3. 模拟测试匹配(各组成部分消息均可匹配)

1.启动Web环境的不同方式


  • @SpringBootTest注解的webEnvironment属性 提供了启动Web环境的选择:

在这里插入图片描述



  • 默认 webEnvironment = SpringBootTest.WebEnvironment.NONE:不启动Web服务器



  • webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT:使用默认端口在测试类启动Web服务器
/**
 * @author .29.
 * @create 2023-04-01 21:39
 */
//webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT:默认端口在测试类启动Web服务器
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class WebTest {
    @Test
    public void test(){

    }
}

在这里插入图片描述



  • webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT:使用随机端口在测试类启动Web服务器
/**
 * @author .29.
 * @create 2023-04-01 21:39
 */

//webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT: 随机端口 在测试类启动Web服务器
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class WebTest {
    @Test
    public void test(){

    }
}

在这里插入图片描述



2.发起虚拟请求


  • 控制层组件:
/**
 * @author .29.
 * @create 2023-04-01 22:38
 */
@RestController
@RequestMapping("/books")
public class BookController {
    @GetMapping
    public String get(){
        System.out.println("get() is running ...");
        return "Springboot";
    }
}

  • 发起MVC虚拟调用,模拟发起请求
/**
 * @author .29.
 * @create 2023-04-01 21:39
 */

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
//@AutoConfigureMockMvc注解:开启MVC虚拟调用
@AutoConfigureMockMvc
public class WebTest {
    @Test  //@Autowired注解,注入虚拟MVC调用对象
    public void testWeb(@Autowired MockMvc mockMvc) throws Exception {
        //创建虚拟请求,当前访问/books
        MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get("/books");
        //执行对应的请求
        mockMvc.perform(builder);
    }
}

成功发起虚拟请求
在这里插入图片描述



3.匹配响应的执行状态


  • 虚拟请求状态匹配:
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
//开启MVC虚拟调用
@AutoConfigureMockMvc
public class WebTest {
    @Test
    public void testStatus(@Autowired MockMvc mockMvc) throws Exception {
        //创建虚拟请求,当前访问/books (这里故意写错,模拟匹配失败)
        MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get("/books1");
        //执行对应的请求
        ResultActions actions = mockMvc.perform(builder);

        //设定预期值 与真实值进行比较,成功测试通过,失败测试失败
        //定义本次调用的预期值
        StatusResultMatchers status = MockMvcResultMatchers.status();
        //预计本次调用是成功的:状态200
        ResultMatcher ok = status.isOk();
        //添加预期值到本次调用过程中,与真实执行结果进行匹配
        actions.andExpect(ok);
    }
}

匹配失败时,输出匹配错误原因:

在这里插入图片描述



4.匹配响应体


/**
 * @author .29.
 * @create 2023-04-01 21:39
 */

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
//开启MVC虚拟调用
@AutoConfigureMockMvc
public class WebTest {
    
    @Test
    public void testBody(@Autowired MockMvc mockMvc) throws Exception {
        MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get("/books");
        ResultActions actions = mockMvc.perform(builder);

        //设定预期值 与真实值进行比较,成功测试通过,失败测试失败
        //定义本次调用的预期值
        ContentResultMatchers content = MockMvcResultMatchers.content();
        //预计请求体为控制层组件的返回值"Springboot 测试类启动web环境 发送虚拟请求"
        //如果请求体反馈JSON数据,string()改为json()
        ResultMatcher body = content.string("Springboot");
        //添加预期值到本次调用过程中,与真实执行结果进行匹配
        actions.andExpect(body);
    }
    
}



5.匹配响应头


    @Test
    public void testHeader(@Autowired MockMvc mockMvc) throws Exception {
        MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get("/books");
        ResultActions actions = mockMvc.perform(builder);

        //设定预期值 与真实值进行比较,成功测试通过,失败测试失败
        //定义本次调用的预期值
        HeaderResultMatchers header = MockMvcResultMatchers.header();
        //预计请求头的Content-Type 为 text/plain;charset=UTF-8
        ResultMatcher string = header.string("Content-Type", "text/plain;charset=UTF-8");
        //添加预期值到本次调用过程中,与真实执行结果进行匹配
        actions.andExpect(string);
    }
}


在这里插入图片描述

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
配置SpringBoot单元测试,可以按照以下步骤进行操作: 1. 引入依赖:在项目的pom.xml文件中添加Spring Boot测试的依赖项。可以使用以下代码片段将依赖项添加到pom.xml文件中: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> ``` 这些依赖项将提供执行单元测试所需的必要库和工具。 2. 添加注解:在需要进行测试的类上添加注解。使用`@RunWith`注解将测试运行器设置为SpringRunner,并使用`@SpringBootTest`注解指定要启动的Spring Boot应用程序的入口类。以下是一个示例: ```java import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest(classes={YourApplication.class}) public class YourTestClass { // 测试方法 } ``` 在上述示例中,`YourApplication.class`应替换为你的Spring Boot应用程序的实际入口类。 3. 编写测试方法:在测试类中编写测试方法,并使用`@Test`注解标记这些方法作为测试方法。你可以在这些方法中编写针对不同功能的测试用例。 这样配置后,你可以使用IDE或者Maven等工具运行单元测试Spring Boot会自动加载应用程序上下文并执行测试方法。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [SpringBoot单元测试配置流程](https://blog.csdn.net/qq_38058674/article/details/123058717)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

.29.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值