Spring全家桶--SpringBoot(三)

简介: Spring全家桶--SpringBoot(三)

3.4.3 断言


简单的断言


断言(assertions)是测试方法中的核心部分,用来对测试需要满足的条件进行验证。这些断言方法都是 org.junit.jupiter.api.Assertions 的静态方法。JUnit 5 内置的断言可以分成如下几个类别:


检查业务逻辑返回的数据是否合理。


所有的测试运行结束以后,会有一个详细的测试报告;


方法 说明

assertEquals 判断两个对象或两个原始类型是否相等

assertNotEquals 判断两个对象或两个原始类型是否不相等

assertSame 判断两个对象引用是否指向同一个对象

assertNotSame 判断两个对象引用是否指向不同的对象

assertTrue 判断给定的布尔值是否为 true

assertFalse 判断给定的布尔值是否为 false

assertNull 判断给定的对象引用是否为 null

assertNotNull 判断给定的对象引用是否不为 null


@Test
@DisplayName("simple assertion")
public void simple() {
     assertEquals(3, 1 + 2, "simple math");
     assertNotEquals(3, 1 + 1);
     assertNotSame(new Object(), new Object());
     Object obj = new Object();
     assertSame(obj, obj);
     assertFalse(1 > 2);
     assertTrue(1 < 2);
     assertNull(null);
     assertNotNull(new Object());
}


数组断言


通过 assertArrayEquals 方法来判断两个对象或原始类型的数组是否相等


@Test
@DisplayName("array assertion")
public void array() {
 assertArrayEquals(new int[]{1, 2}, new int[] {1, 2});
}


组合断言


assertAll 方法接受多个 org.junit.jupiter.api.Executable 函数式接口的实例作为要验证的断言,可以通过 lambda 表达式很容易的提供这些断言


@Test
@DisplayName("assert all")
public void all() {
 assertAll("Math",
    () -> assertEquals(2, 1 + 1),
    () -> assertTrue(1 > 0)
 );
}


异常断言


在JUnit4时期,想要测试方法的异常情况时,需要用**@Rule注解的ExpectedException变量还是比较麻烦的。而JUnit5提供了一种新的断言方式Assertions.assertThrows()** ,配合函数式编程就可以进行使用。


@Test
@DisplayName("异常测试")
public void exceptionTest() {
    ArithmeticException exception = Assertions.assertThrows(
           //扔出断言异常
            ArithmeticException.class, () -> System.out.println(1 % 0));
}


超时断言


Junit5还提供了Assertions.assertTimeout() 为测试方法设置了超时时间


@Test
@DisplayName("超时测试")
public void timeoutTest() {
    //如果测试方法时间超过1s将会异常
    Assertions.assertTimeout(Duration.ofMillis(1000), () -> Thread.sleep(500));
}


快速失败


通过 fail 方法直接使得测试失败


@Test
@DisplayName("fail")
public void shouldFail() {
 fail("This should fail");
}


3.4.4 前置条件(assumptions)


JUnit 5 中的前置条件(assumptions【假设】)类似于断言,不同之处在于不满足的断言会使得测试方法失败,而不满足的前置条件只会使得测试方法的执行终止。前置条件可以看成是测试方法执行的前提,当该前提不满足时,就没有继续执行的必要。


@DisplayName("前置条件")
public class AssumptionsTest {
 private final String environment = "DEV";
 @Test
 @DisplayName("simple")
 public void simpleAssume() {
    assumeTrue(Objects.equals(this.environment, "DEV"));
    assumeFalse(() -> Objects.equals(this.environment, "PROD"));
 }
 @Test
 @DisplayName("assume then do")
 public void assumeThenDo() {
    assumingThat(
       Objects.equals(this.environment, "DEV"),
       () -> System.out.println("In DEV")
    );
 }
}


assumeTrue 和 assumFalse 确保给定的条件为 true 或 false,不满足条件会使得测试执行终止。assumingThat 的参数是表示条件的布尔值和对应的 Executable 接口的实现对象。只有条件满足时,Executable 对象才会被执行;当条件不满足时,测试执行并不会终止。


3.4.5 嵌套测试


JUnit 5 可以通过 Java 中的内部类和@Nested 注解实现嵌套测试,从而可以更好的把相关的测试方法组织在一起。在内部类中可以使用@BeforeEach 和@AfterEach 注解,而且嵌套的层次没有限制。


@DisplayName("A stack")
class TestingAStackDemo {
    Stack<Object> stack;
    @Test
    @DisplayName("is instantiated with new Stack()")
    void isInstantiatedWithNew() {
        new Stack<>();
    }
    @Nested
    @DisplayName("when new")
    class WhenNew {
        @BeforeEach
        void createNewStack() {
            stack = new Stack<>();
        }
        @Test
        @DisplayName("is empty")
        void isEmpty() {
            assertTrue(stack.isEmpty());
        }
        @Test
        @DisplayName("throws EmptyStackException when popped")
        void throwsExceptionWhenPopped() {
            assertThrows(EmptyStackException.class, stack::pop);
        }
        @Test
        @DisplayName("throws EmptyStackException when peeked")
        void throwsExceptionWhenPeeked() {
            assertThrows(EmptyStackException.class, stack::peek);
        }
        @Nested
        @DisplayName("after pushing an element")
        class AfterPushing {
            String anElement = "an element";
            @BeforeEach
            void pushAnElement() {
                stack.push(anElement);
            }
            @Test
            @DisplayName("it is no longer empty")
            void isNotEmpty() {
                assertFalse(stack.isEmpty());
            }
            @Test
            @DisplayName("returns the element when popped and is empty")
            void returnElementWhenPopped() {
                assertEquals(anElement, stack.pop());
                assertTrue(stack.isEmpty());
            }
            @Test
            @DisplayName("returns the element when peeked but remains not empty")
            void returnElementWhenPeeked() {
                assertEquals(anElement, stack.peek());
                assertFalse(stack.isEmpty());
            }
        }
    }
}


3.5.6 参数化测试

参数化测试是JUnit5很重要的一个新特性,它使得用不同的参数多次运行测试成为了可能,也为我们的单元测试带来许多便利。


利用**@ValueSource**等注解,指定入参,我们将可以使用不同的参数进行多次单元测试,而不需要每新增一个参数就新增一个单元测试,省去了很多冗余代码。


@ValueSource: 为参数化测试指定入参来源,支持八大基础类以及String类型,Class类型


@NullSource: 表示为参数化测试提供一个null的入参


@EnumSource: 表示为参数化测试提供一个枚举入参


@CsvFileSource:表示读取指定CSV文件内容作为参数化测试入参


@MethodSource:表示读取指定方法的返回值作为参数化测试入参(注意方法返回需要是一个流)


当然如果参数化测试仅仅只能做到指定普通的入参还达不到让我觉得惊艳的地步。让我真正感到他的强大之处的地方在于他可以支持外部的各类入参。如:CSV,YML,JSON 文件甚至方法的返回值也可以作为入参。只需要去实现ArgumentsProvider接口,任何外部文件都可以作为它的入参。


@ParameterizedTest
@ValueSource(strings = {"one", "two", "three"})
@DisplayName("参数化测试1")
public void parameterizedTest1(String string) {
    System.out.println(string);
    Assertions.assertTrue(StringUtils.isNotBlank(string));
}
@ParameterizedTest
@MethodSource("method")    //指定方法名
@DisplayName("方法来源参数")
public void testWithExplicitLocalMethodSource(String name) {
    System.out.println(name);
    Assertions.assertNotNull(name);
}
static Stream<String> method() {
    return Stream.of("apple", "banana");
}


3.5 指标监控


3.5.1 SpringBoot Actuator


未来每一个微服务在云上部署以后,我们都需要对其进行监控、追踪、审计、控制等。SpringBoot就抽取了Actuator场景,使得我们每个微服务快速引用即可获得生产级别的应用监控、审计等功能。


<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>


1.0和2.0的区别


image.png


如何使用


引入场景


访问 http://localhost:8080/actuator/**


暴露所有监控信息为HTTP


management:

 endpoints:

   enabled-by-default: true #暴露所有端点信息

   web:

     exposure:

       include: '*'  #以web方式暴露


测试


http://localhost:8080/actuator/beans


http://localhost:8080/actuator/configprops


http://localhost:8080/actuator/metrics


http://localhost:8080/actuator/metrics/jvm.gc.pause


http://localhost:8080/actuator/endpointName/detailPath


可视化


https://github.com/codecentric/spring-boot-admin


3.5.2 Actuator Endpoint


最常使用的端点


ID 描述

auditevents 暴露当前应用程序的审核事件信息。需要一个AuditEventRepository组件。

beans 显示应用程序中所有Spring Bean的完整列表。

caches 暴露可用的缓存。

conditions 显示自动配置的所有条件信息,包括匹配或不匹配的原因。

configprops 显示所有@ConfigurationProperties。

env 暴露Spring的属性ConfigurableEnvironment

flyway 显示已应用的所有Flyway数据库迁移。 需要一个或多个Flyway组件。

health 显示应用程序运行状况信息。

httptrace 显示HTTP跟踪信息(默认情况下,最近100个HTTP请求-响应)。需要一个HttpTraceRepository组件。

info 显示应用程序信息。

integrationgraph 显示Spring integrationgraph 。需要依赖spring-integration-core。

loggers 显示和修改应用程序中日志的配置。

liquibase 显示已应用的所有Liquibase数据库迁移。需要一个或多个Liquibase组件。

metrics 显示当前应用程序的“指标”信息。

mappings 显示所有@RequestMapping路径列表。

scheduledtasks 显示应用程序中的计划任务。

sessions 允许从Spring Session支持的会话存储中检索和删除用户会话。需要使用Spring Session的基于Servlet的Web应用程序。

shutdown 使应用程序正常关闭。默认禁用。

startup 显示由ApplicationStartup收集的启动步骤数据。需要使用SpringApplication进行配置BufferingApplicationStartup。

threaddump 执行线程转储。

如果您的应用程序是Web应用程序(Spring MVC,Spring WebFlux或Jersey),则可以使用以下附加端点:


ID 描述

heapdump 返回hprof堆转储文件。

jolokia 通过HTTP暴露JMX bean(需要引入Jolokia,不适用于WebFlux)。需要引入依赖jolokia-core。

logfile 返回日志文件的内容(如果已设置logging.file.name或logging.file.path属性)。支持使用HTTPRange标头来检索部分日志文件的内容。

prometheus 以Prometheus服务器可以抓取的格式公开指标。需要依赖micrometer-registry-prometheus。

最常用的Endpoint


Health:监控状况


Metrics:运行时指标


Loggers:日志记录


Health Endpoint


健康检查端点,我们一般用于在云平台,平台会定时的检查应用的健康状况,我们就需要Health Endpoint可以为平台返回当前应用的一系列组件健康状况的集合。


重要的几点:


health endpoint返回的结果,应该是一系列健康检查后的一个汇总报告


很多的健康检查默认已经自动配置好了,比如:数据库、redis等


可以很容易的添加自定义的健康检查机制


访问如下网址即可查看健康检查


localhost:8080/actuator/health


image.png


Metrics Endpoint


metrics 度量


Endpoint 端点


提供详细的、层级的、空间指标信息,这些信息可以被pull(主动推送)或者push(被动获取)方式得到;


通过Metrics对接多种监控系统


简化核心Metrics开发


添加自定义Metrics或者扩展已有Metrics


image.png


管理Endpoint


开启与禁用Endpoints


默认所有的Endpoint除过shutdown都是开启的。

需要开启或者禁用某个Endpoint。配置模式为 management.endpoint..enabled = true


management:
  endpoint:
    beans:
      enabled: true


或者禁用所有的Endpoint然后手动开启指定的Endpoint


/

management:
  endpoints:
    enabled-by-default: false
  endpoint:
    beans:
      enabled: true
    health:
      enabled: true

暴露Endpoints


支持的暴露方式


HTTP:默认只暴露health和info Endpoint


JMX:默认暴露所有Endpoint


除过health和info,剩下的Endpoint都应该进行保护访问。如果引入SpringSecurity,则会默认配置安全访问规则


ID JMX Web

auditevents Yes No

beans Yes No

caches Yes No

conditions Yes No

configprops Yes No

env Yes No

flyway Yes No

health Yes Yes

heapdump N/A No

httptrace Yes No

info Yes Yes

integrationgraph Yes No

jolokia N/A No

logfile N/A No

loggers Yes No

liquibase Yes No

metrics Yes No

mappings Yes No

prometheus N/A No

scheduledtasks Yes No

sessions Yes No

shutdown Yes No

startup Yes No

threaddump Yes No


3.5.3 定制Endpoint


定制 Health 信息


import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.stereotype.Component;
@Component
public class MyHealthIndicator implements HealthIndicator {
    @Override
    public Health health() {
        int errorCode = check(); // perform some specific health check
        if (errorCode != 0) {
            return Health.down().withDetail("Error Code", errorCode).build();
        }
        return Health.up().build();
    }
}
构建Health
Health build = Health.down()
                .withDetail("msg", "error service")
                .withDetail("code", "500")
                .withException(new RuntimeException())
                .build();
management:
    health:
      enabled: true
      show-details: always #总是显示详细信息。可显示每个模块的状态信息


@Component
public class MyComHealthIndicator extends AbstractHealthIndicator {
    /**
     * 真实的检查方法
     * @param builder
     * @throws Exception
     */
    @Override
    protected void doHealthCheck(Health.Builder builder) throws Exception {
        //mongodb。  获取连接进行测试
        Map<String,Object> map = new HashMap<>();
        // 检查完成
        if(1 == 2){
//            builder.up(); //健康
            builder.status(Status.UP);
            map.put("count",1);
            map.put("ms",100);
        }else {
//            builder.down();
            builder.status(Status.OUT_OF_SERVICE);
            map.put("err","连接超时");
            map.put("ms",3000);
        }
        builder.withDetail("code",100)
                .withDetails(map);
    }
}


定制info信息


常用两种方式


编写配置文件

info:
  appName: boot-admin
  version: 2.0.1
  mavenProjectName: @project.artifactId@  #使用@@可以获取maven的pom文件值
  mavenProjectVersion: @project.version@


编写InfoContributor


import java.util.Collections;
import org.springframework.boot.actuate.info.Info;
import org.springframework.boot.actuate.info.InfoContributor;
import org.springframework.stereotype.Component;
@Component
public class ExampleInfoContributor implements InfoContributor {
    @Override
    public void contribute(Info.Builder builder) {
        builder.withDetail("example",
                Collections.singletonMap("key", "value"));
    }
}


http://localhost:8080/actuator/info 会输出以上方式返回的所有info信息


3.6 原理解析


3.6.1 Profile功能


为了方便多环境适配,springboot简化了profile功能。


默认配置文件 application.yaml;任何时候都会加载


指定环境配置文件 application-{env}.yaml


激活指定环境


配置文件激活

命令行激活:java -jar xxx.jar –spring.profiles.active=prod --person.name=haha

修改配置文件的任意值,命令行优先

默认配置与环境配置同时生效


同名配置项,profile配置优先


测试


package com.caq.admin.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController02 {
    //${}是取值运算符,之后的:后面的意思是默认值
    @Value("${person.name:ls}")
    private String name;
    @GetMapping("/test2")
    public String hello(){
        return "hello" + name;
    }
}


默认配置文件application.yml


为空


#person.name=zs


生产环境配置文件application-prod.yml


person:
  name: prod-zs


测试环境配置文件application-test.yml


person:
  name: test-zs


启动SpringBoot,访问测试


package com.caq.admin;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@MapperScan("com.caq.admin")
@SpringBootApplication
public class SbMpApplication {
    public static void main(String[] args) {
        SpringApplication.run(SbMpApplication.class, args);
    }
}


默认配置文件application.yml


为空


#person.name=zs
spring:
  profiles:
    active: test


生产环境配置文件application-prod.yml


person:
  name: prod-zs
server:
  port: 8080


测试环境配置文件application-test.yml


person:
  name: test-zs
server:
  port: 8000


image.png


3.6.2 外部化配置


Profile功能


为了方便多环境适配,springboot简化了profile功能。


application-profile功能

默认配置文件 application.yaml;任何时候都会加载


指定环境配置文件 application-{env}.yaml


激活指定环境


配置文件激活

命令行激活:java -jar xxx.jar –spring.profiles.active=prod --person.name=haha

修改配置文件的任意值,命令行优先

默认配置与环境配置同时生效


同名配置项,profile配置优先


@Profile条件装配功能
@Configuration(proxyBeanMethods = false)
@Profile("production")
public class ProductionConfiguration {
    // ...
}


profile分组

spring.profiles.group.production[0]=proddb

spring.profiles.group.production[1]=prodmq


使用:--spring.profiles.active=production  激活


相关文章
|
前端开发 Java 应用服务中间件
《深入理解Spring》 Spring Boot——约定优于配置的革命者
Spring Boot基于“约定优于配置”理念,通过自动配置、起步依赖、嵌入式容器和Actuator四大特性,简化Spring应用的开发与部署,提升效率,降低门槛,成为现代Java开发的事实标准。
|
前端开发 Java 微服务
《深入理解Spring》:Spring、Spring MVC与Spring Boot的深度解析
Spring Framework是Java生态的基石,提供IoC、AOP等核心功能;Spring MVC基于其构建,实现Web层MVC架构;Spring Boot则通过自动配置和内嵌服务器,极大简化了开发与部署。三者层层演进,Spring Boot并非替代,而是对前者的高效封装与增强,适用于微服务与快速开发,而深入理解Spring Framework有助于更好驾驭整体技术栈。
|
XML Java 应用服务中间件
【SpringBoot(一)】Spring的认知、容器功能讲解与自动装配原理的入门,带你熟悉Springboot中基本的注解使用
SpringBoot专栏开篇第一章,讲述认识SpringBoot、Bean容器功能的讲解、自动装配原理的入门,还有其他常用的Springboot注解!如果想要了解SpringBoot,那么就进来看看吧!
1077 2
|
人工智能 Java 机器人
基于Spring AI Alibaba + Spring Boot + Ollama搭建本地AI对话机器人API
Spring AI Alibaba集成Ollama,基于Java构建本地大模型应用,支持流式对话、knife4j接口可视化,实现高隐私、免API密钥的离线AI服务。
8087 2
基于Spring AI Alibaba + Spring Boot + Ollama搭建本地AI对话机器人API
存储 JSON Java
1215 0
|
人工智能 Java 开发者
【Spring】原理解析:Spring Boot 自动配置
Spring Boot通过“约定优于配置”的设计理念,自动检测项目依赖并根据这些依赖自动装配相应的Bean,从而解放开发者从繁琐的配置工作中解脱出来,专注于业务逻辑实现。
3254 0
|
监控 Java API
Spring Boot 3.2 结合 Spring Cloud 微服务架构实操指南 现代分布式应用系统构建实战教程
Spring Boot 3.2 + Spring Cloud 2023.0 微服务架构实践摘要 本文基于Spring Boot 3.2.5和Spring Cloud 2023.0.1最新稳定版本,演示现代微服务架构的构建过程。主要内容包括: 技术栈选择:采用Spring Cloud Netflix Eureka 4.1.0作为服务注册中心,Resilience4j 2.1.0替代Hystrix实现熔断机制,配合OpenFeign和Gateway等组件。 核心实操步骤: 搭建Eureka注册中心服务 构建商品
1785 3
|
前端开发 Java Maven
Spring 和 Spring Boot 之间的比较
本文对比了标准Spring框架与Spring Boot的区别,重点分析两者在模块使用(如MVC、Security)上的差异。Spring提供全面的Java开发基础设施支持,包含依赖注入和多种开箱即用的模块;而Spring Boot作为Spring的扩展,通过自动配置、嵌入式服务器等功能简化开发流程。文章还探讨了两者的Maven依赖、Mvc配置、模板引擎配置、启动方式及打包部署等方面的异同,展示了Spring Boot如何通过减少样板代码和配置提升开发效率。总结指出,Spring Boot是Spring的增强版,使应用开发、测试与部署更加便捷高效。
1962 11