Springboot测试

1.加载测试专用属性

主要为@SpringBootTest中properties属性和args属性

package com.example;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.validation.annotation.Validated;

//添加临时属性,优先级大于application.yml中的属性
//properties为当前测试类添加临时属性
//@SpringBootTest(properties = {"test.prop=testValue1"})
//args属性可以为当前测试用例添加临时的命令行参数
//@SpringBootTest(args = {"--test.prop=testValue2"})
//args的优先级最高
@SpringBootTest(properties = {"test.prop=testValue1"},args = {"--test.prop=testValue2"})
class Springboot02TestApplicationTests {
    @Value("${test.prop}")
    private String msg;

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

2.加载测试专用配置

用例
项目结构
在这里插入图片描述
MsgConfig.class

package com.example.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MsgConfig {

    @Bean
    public String message(){
        return "message";
    }
}

ConfigurationTest.class

package com.example;

import com.example.config.MsgConfig;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Import;

@SpringBootTest
@Import(MsgConfig.class)
public class ConfigurationTest {
    @Autowired
    private String msg;

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

3.表现层测试

使用webEnvironment属性开启tomcat,具体代码如下:

项目结构
在这里插入图片描述
BookController.class

package com.example.controller;

import com.example.domain.Book;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.xml.ws.RequestWrapper;

@RestController
@RequestMapping("/book")
public class BookController {
    /*@GetMapping
    public String getById(){
        System.out.println("getById is running.....");
        return "Springboot";
    }*/

    @GetMapping
    public Book getById(){
        Book book=new Book();
        book.setId(1);
        book.setName("流浪地球");
        book.setType("科幻");
        return book;
    }
}

Book.class

package com.example.domain;

import lombok.Data;

@Data
public class Book {
    private int id;
    private String name;
    private String type;
}

WebTest.class

package com.example;

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.mock.web.MockHttpServletRequest;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.ResultMatcher;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.ContentResultMatchers;
import org.springframework.test.web.servlet.result.HeaderResultMatchers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.result.StatusResultMatchers;

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)

//开启虚拟调用
@AutoConfigureMockMvc
public class WebTest {
    @Autowired
    private MockMvc mvc;

    @Test
    void testWeb() throws Exception {
        //创建一个虚拟的请求
        MockHttpServletRequestBuilder build= MockMvcRequestBuilders.get("/book");
        mvc.perform(build);
    }


    //状态匹配
    @Test
    void testStatus() throws Exception {
        //创建一个虚拟的请求
        MockHttpServletRequestBuilder build= MockMvcRequestBuilders.get("/book");
        ResultActions action = mvc.perform(build);

        //设定预期值,与真实值进行比较,成功测试通过
        //定义本次调用的预期值
        StatusResultMatchers status = MockMvcResultMatchers.status();
        //预期本次调用成功
        ResultMatcher ok = status.isOk();
        //添加预期值到本次调用过程中进行匹配
        action.andExpect(ok);
    }

    //字符串匹配

    @Test
    void testBody() throws Exception {
        //创建一个虚拟的请求
        MockHttpServletRequestBuilder build= MockMvcRequestBuilders.get("/book");
        ResultActions action = mvc.perform(build);

        //设定预期值,与真实值进行比较,成功测试通过
        //定义本次调用的预期值
        ContentResultMatchers content = MockMvcResultMatchers.content();
        //预期本次调用成功
        ResultMatcher result = content.string("springboot");
        //添加预期值到本次调用过程中进行匹配
        action.andExpect(result);
    }


    //json匹配

    @Test
    void testJson() throws Exception {
        //创建一个虚拟的请求
        MockHttpServletRequestBuilder build= MockMvcRequestBuilders.get("/book");
        ResultActions action = mvc.perform(build);

        //设定预期值,与真实值进行比较,成功测试通过
        //定义本次调用的预期值
        ContentResultMatchers content = MockMvcResultMatchers.content();
        //预期本次调用成功
        ResultMatcher result = content.json("{\"id\":1,\"name\":\"流浪地球\",\"type\":\"科幻\"}");
        //添加预期值到本次调用过程中进行匹配
        action.andExpect(result);
    }

    //ContentType匹配

    @Test
    void testContentType() throws Exception {
        //创建一个虚拟的请求
        MockHttpServletRequestBuilder build= MockMvcRequestBuilders.get("/book");
        ResultActions action = mvc.perform(build);

        //设定预期值,与真实值进行比较,成功测试通过
        //定义本次调用的预期值
        HeaderResultMatchers header = MockMvcResultMatchers.header();
        //预期本次调用成功
        ResultMatcher contentType = header.string("Content-Type", "application/json");
        //添加预期值到本次调用过程中进行匹配
        action.andExpect(contentType);
    }

    @Test
    void testGetById() throws Exception {
        //创建一个虚拟的请求
        MockHttpServletRequestBuilder build= MockMvcRequestBuilders.get("/book");
        ResultActions action = mvc.perform(build);


        //设定预期值,与真实值进行比较,成功测试通过
        //定义本次调用的预期值
        StatusResultMatchers status = MockMvcResultMatchers.status();
        //预期本次调用成功
        ResultMatcher ok = status.isOk();
        //添加预期值到本次调用过程中进行匹配
        action.andExpect(ok);


        //设定预期值,与真实值进行比较,成功测试通过
        //定义本次调用的预期值
        ContentResultMatchers content = MockMvcResultMatchers.content();
        //预期本次调用成功
        ResultMatcher result = content.json("{\"id\":1,\"name\":\"流浪地球\",\"type\":\"科幻\"}");
        //添加预期值到本次调用过程中进行匹配
        action.andExpect(result);

        //设定预期值,与真实值进行比较,成功测试通过
        //定义本次调用的预期值
        HeaderResultMatchers header = MockMvcResultMatchers.header();
        //预期本次调用成功
        ResultMatcher contentType = header.string("Content-Type", "application/json");
        //添加预期值到本次调用过程中进行匹配
        action.andExpect(contentType);
    }
}

4.业务层测试回滚

想在Springboot中做业务层相关的测试,但是又不想留下数据在数据库中,则只需在测试类上添加@Transactional注解即可。

5.测试用例使用随机值

在这里插入图片描述

总结

参考视频

这部分内容作为了解使用。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
回答: 在Spring Boot中进行单元测试非常简单。你可以使用@SpringBootTest注解来指定测试类,并且可以通过配置webEnvironment属性来自定义测试环境。如果你需要自定义测试属性文件,可以使用@TestPropertySource注解。同时,你需要在pom.xml文件中添加spring-boot-starter-test依赖。这样就可以使用Spring Boot提供的测试功能了。下面是一个示例的Spring Boot测试类的代码: ```java import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.test.context.junit4.SpringRunner; import java.util.List; @RunWith(SpringRunner.class) @SpringBootTest public class SpringbootTest { @Autowired private DiscoveryClient discoveryClient; @Test public void NacosTest() { List<String> services = discoveryClient.getServices(); services.forEach(x-> System.out.println(x)); } } ``` 这个测试类使用了Spring Boot提供的注解@RunWith和@SpringBootTest来指定测试环境,并且通过@Autowired注解来注入需要测试的组件。在测试方法中,我们可以使用这些组件进行测试操作。在这个示例中,我们使用了DiscoveryClient来获取服务列表并打印出来。 #### 引用[.reference_title] - *1* [Spring Boot中的测试](https://blog.csdn.net/superfjj/article/details/104206183)[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^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [springboot(16)Spring Boot使用单元测试](https://blog.csdn.net/sz85850597/article/details/80427408)[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^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [SpringBoot测试类](https://blog.csdn.net/m0_67403076/article/details/126115129)[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^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值