【springboot单元测试,集成测试】

这篇具有很好参考价值的文章主要介绍了【springboot单元测试,集成测试】。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

本文介绍一下SpringBoot中的测试方法

集成测试

@SpringBootTest

一个普通的web api

@RequestMapping
@RestController
public class HelloController {

    @Autowired
    RestTemplate restTemplate;

    @GetMapping(value = "/api/hi")
    public Map<String,Object> hello() {

        String baiduRes = restTemplate.getForObject("https://www.baidu.com", String.class);
        Map<String, Object> res = new HashMap<>();
        res.put("status", "中");
        res.put("msg", baiduRes);
        return res;
    }
}

测试类:


package xyz.bliu.sptest;


import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.client.RestTemplate;

import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@SpringBootTest
public class ControllerTest02 {

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    MockMvc mockMvc;

    @Test
    public void restTemplateShouldNotNull() {
        assertThat(restTemplate).isNotNull();
    }

    @Test
    public void testGetRequest() throws Exception {

        mockMvc.perform(get("/api/hi"))
               .andExpect(status().isOk())
               .andDo(print());
    }
}

使用mockMvc好处是不会启动真实的web服务
当然你可以使用@SpingBootTest 并且注入一个RestTemplate来做真实的请求

假如希望仅仅测试controller层时, 可以使用另外一个注解
@WebMvcTest
他有一个参数可以指定测试的controller


package xyz.bliu.sptest;


import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.client.RestTemplate;
import xyz.bliu.sptest.controller.HelloController;

import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;

@WebMvcTest(controllers = HelloController.class)
public class ControllerTest01 {


    @Autowired
    MockMvc mockMvc;

    @MockBean
    RestTemplate restTemplate;

    @Test
    public void helloShouldOK() throws Exception {

        when(restTemplate.getForObject("https://www.baidu.com", String.class)).thenReturn("haha");

        assertThat(mockMvc).isNotNull();
        mockMvc.perform(get("/api/hi").header("kk", "v1")
                        .header("Content-Type", "application/json"))
                .andDo(print())
                .andExpect(content().contentType("application/json"))
                .andExpect(content().json("{'status':'中', 'msg':'haha'}"));
    }


    @Test
    public void restTemplateShouldBeNull() {
        assertThat(restTemplate).isNull();
    }
}

这样仅会加载指定的controller和一些web层的东西不会加载其他Bean
假如这个controller中依赖其他的bean怎么办呢?
答案是需要使用@MockBean去Mock依赖的行为

例如我这里的处理

 @MockBean
 RestTemplate restTemplate;

 when(restTemplate.getForObject("https://www.baidu.com", String.class)).thenReturn("haha");

其实就是说当调用restTemplate.getForObject(“https://www.baidu.com”, String.class)时,方法会返回“haha”


@WebMvcTest VS @SpringBootTest

显然当你只需要测试你的controller接收请求参数或者返回值时你可以使用@WebMvcTest, 因为它不需要加载整个application context, 因此会使你的test更快

然而当需要集成测试时则需要@SpringBootTest
并且他们是不能同时使用的

  • 另外你可能注意到了AssertJ 提供的 assertThat api非常好用,可以流式调用

  • 另外本文测试环境为spring boot 3.x 和 Junit5
    如果你使用是springboot 2.x 你可能还需要 @RunWith(SpringRuner.class) ( junit4)或者 @extendwith(springextension.class) (junit5)文章来源地址https://www.toymoban.com/news/detail-717477.html

当然你可以使用@SpingBootTest 并且注入一个RestTemplate来做真实的请求

package xyz.bliu.sptest;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

import static org.assertj.core.api.Assertions.assertThat;

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class ControllerTest03 {


    @Autowired
    RestTemplate restTemplate;

    @LocalServerPort
    int port;

    @Test
    public void testGet() {
        Map resp = restTemplate.getForObject("http://localhost:"+port+ "/api/hi", Map.class);
        assertThat(resp.get("status").toString()).isEqualTo("中");
    }
}

到了这里,关于【springboot单元测试,集成测试】的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 【springboot单元测试,集成测试】

    本文介绍一下SpringBoot中的测试方法 @SpringBootTest 一个普通的web api 测试类: 使用mockMvc好处是不会启动真实的web服务 当然你可以使用@SpingBootTest 并且注入一个RestTemplate来做真实的请求 假如希望仅仅测试controller层时, 可以使用另外一个注解 @WebMvcTest 他有一个参数可以指定测试

    2024年02月08日
    浏览(25)
  • 单元测试之 - Spring框架提供的单元/集成测试注解

    Spring框架提供了很多注解来辅助完成单元测试和集成测试(备注:这里的集成测试指容器内部的集成测试,非系统间的集成测试),先看看Spring框架提供了哪些注解以及对应的作用。 @RunWith(SpringRunner.class) / @ExtendWith(SpringExtension.class) : 用于在测试类中启用 Spring 框架的支持。

    2024年02月14日
    浏览(33)
  • 【Spring Boot】单元测试

    单元测试在日常项目开发中必不可少,Spring Boot提供了完善的单元测试框架和工具用于测试开发的应用。接下来介绍Spring Boot为单元测试提供了哪些支持,以及如何在Spring Boot项目中进行单元测试。 单元测试主要用于测试单个代码组件,以确保代码按预期方式工作。目前流行的

    2024年02月16日
    浏览(38)
  • Spring Boot单元测试

    ❤️❤️❤️SSM专栏更新中,各位大佬觉得写得不错,支持一下,感谢了!❤️❤️❤️ Spring + Spring MVC + MyBatis_冷兮雪的博客-CSDN博客 Spring Boot 中进行单元测试是一个常见的做法,可以帮助你验证应用程序的各个组件是否按预期工作。所以我们有必要去学习一番! 单元测试

    2024年02月13日
    浏览(36)
  • SpringBoot 集成Junit单元测试

    学习文章: https://www.cnblogs.com/ysocean/p/6889906.html 开发工具: IDEA 2022.1.4 目录 目录 1. 概述  2. 实现步骤         2.1 maven导入依赖          2.2 随意代码演示(不推荐)         2.3 规范代码演示(推荐) 3. Junit相关其他注解 4. 注意事项 5. 结语         接触到Junit,应该是看

    2024年02月09日
    浏览(25)
  • Spring Boot 单元测试,保姆级教程!

    概念: 单元测试(unit testing),是指对软件中的最小可测试单元进行检查和验证。在Java中单元测试的最小单元是类。 单元测试是开发者编写的一小段代码,用于检验被测代码的一个很小的、很明确的功能是否正确。执行单元测试,就是为了证明这段代码的行为和我们期望是

    2024年02月03日
    浏览(36)
  • Spring Boot 单元测试 0基础教程

    咱们以一种通俗易懂的方式,通过一个简单的实例来教你怎么在Spring Boot项目中进行单元测试。 假设你有一个简单的Spring Boot应用,里面有一个UserService接口,以及它的实现类 UserServiceImpl,这个服务有一个方法用来获取用户的问候语。 为了对该方法进行单元测试,我们可以创

    2024年04月16日
    浏览(31)
  • Spring Boot异常处理和单元测试

    SpringBoot默认的处理异常的机制:SpringBoot 默认的已经提供了一套处理异常的机制。一旦程序中出现了异常 SpringBoot 会向/error 的 url 发送请求。在 springBoot 中提供了一个叫 BasicErrorController 来处理/error 请求,然后跳转到默认显示异常的页面来展示异常信息 如 果我 们 需 要 将 所

    2024年03月17日
    浏览(30)
  • Spring Boot 做单元测试,真心强悍!

    Spring Boot 提供了丰富的测试功能,主要由以下两个模块组成: spring-boot-test :提供测试核心功能。 spring-boot-test-autoconfigure :提供对测试的自动配置。 Spring Boot 提供了一个  spring-boot-starter-test 一站式启动器,如以下依赖配置所示。 测试启动器依赖不仅包含以上两个 Spring Bo

    2024年02月04日
    浏览(34)
  • Spring Boot单元测试入门指南

    JUnit是一个成熟和广泛应用的Java单元测试框架,它提供了丰富的功能和灵活的扩展机制,可以帮助开发人员编写高质量的单元测试。通过JUnit,开发人员可以更加自信地进行重构、维护和改进代码,同时提高代码质量和可维护性。 在使用Spring Boot进行单元测试时,以下是一些

    2024年02月15日
    浏览(33)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包