国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

【SpringBoot3】--03.數(shù)據(jù)訪問、基礎(chǔ)特性(外部化和內(nèi)部外配置、整合JUnit)

這篇具有很好參考價(jià)值的文章主要介紹了【SpringBoot3】--03.數(shù)據(jù)訪問、基礎(chǔ)特性(外部化和內(nèi)部外配置、整合JUnit)。希望對(duì)大家有所幫助。如果存在錯(cuò)誤或未考慮完全的地方,請(qǐng)大家不吝賜教,您也可以點(diǎn)擊"舉報(bào)違法"按鈕提交疑問。


學(xué)習(xí)視頻: 尚硅谷SpringBoot3視頻

SpringBoot3-數(shù)據(jù)訪問

1.整合SSM場(chǎng)景

SpringBoot 整合 SpringSpringMVC、MyBatis 進(jìn)行數(shù)據(jù)訪問場(chǎng)景開發(fā)

1.1創(chuàng)建SSM整合項(xiàng)目

【SpringBoot3】--03.數(shù)據(jù)訪問、基礎(chǔ)特性(外部化和內(nèi)部外配置、整合JUnit),Java,spring boot,junit,java

勾選之后會(huì)導(dǎo)入以下包

<!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>3.0.1</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>

1.2配置數(shù)據(jù)源

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.type=com.zaxxer.hikari.HikariDataSource
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=root

安裝MyBatisX 插件,幫我們生成Mapper接口的xml文件即可
在接口處 : Alt + 回車

1.3配置MyBatis

必須把mapper的xml文件映射位置在配置文件定義!
而駝峰命名轉(zhuǎn)換建議也開啟

#指定mapper映射文件位置
mybatis.mapper-locations=classpath:/mapper/*.xml
#駝峰命名轉(zhuǎn)換
mybatis.configuration.map-underscore-to-camel-case=true

1.4CRUD編寫

  • 編寫B(tài)ean
package com.atguigu.boot.ssm.bean;

import lombok.Data;

@Data
public class TUser {
    private Integer id;
    private String loginName;
    private String nickName;
    private String passwd;
}
  • 編寫Mapper
public interface UserMapper {
    
    public TUser getUserById(@Param("id") Long id);

}
  • 使用mybatisx插件,快速生成MapperXML
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.atguigu.boot.ssm.mapper.UserMapper">


    <select id="getUserById" resultType="com.atguigu.boot.ssm.bean.TUser">
        select * from t_user where id=#{id}
    </select>
</mapper>
  • 測(cè)試CRUD

UserController

@RestController
public class UserController {
    @Autowired
    UserMapper userMapper;
    @GetMapping("/user/{id}")
    public TUser getUser(@PathVariable("id") Long id){
        TUser user = userMapper.getUserById(id);
        return user;
    }
}
/**
 * 1.@MapperScan告訴Mybatis,掃描哪個(gè)包下面的所有接口
 * 2.使用mybatis.mapper-locations 告訴mybatis,每個(gè)接口的xml文件都在哪里
 */
@MapperScan(basePackages = "com.atguigu.boot.ssm.mapper")
@SpringBootApplication
public class Boot05SsmApplication {

    public static void main(String[] args) {
        SpringApplication.run(Boot05SsmApplication.class, args);
    }

}

運(yùn)行結(jié)果:

【SpringBoot3】--03.數(shù)據(jù)訪問、基礎(chǔ)特性(外部化和內(nèi)部外配置、整合JUnit),Java,spring boot,junit,java

2.自動(dòng)配置原理

  1. 導(dǎo)入 mybatis-spring-boot-starter
  2. 配置數(shù)據(jù)源信息
  3. 配置mybatis的 mapper接口掃描xml映射文件掃描
  4. 編寫bean,mapper,生成xml,編寫sql 進(jìn)行crud。事務(wù)等操作依然和Spring中用法一樣
  5. 效果:
    - 所有sql寫在xml中
    - 所有mybatis配置寫在application.properties下面
  • jdbc場(chǎng)景的自動(dòng)配置

    • mybatis-spring-boot-starter導(dǎo)入 spring-boot-starter-jdbc,jdbc是操作數(shù)據(jù)庫(kù)的場(chǎng)景

    • Jdbc場(chǎng)景的幾個(gè)自動(dòng)配置

      • org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration

        • 數(shù)據(jù)源的自動(dòng)配置
        • 所有和數(shù)據(jù)源有關(guān)的配置都綁定在DataSourceProperties
        • 默認(rèn)使用 HikariDataSource
      • org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration

        • 給容器中放了JdbcTemplate操作數(shù)據(jù)庫(kù)
      • org.springframework.boot.autoconfigure.jdbc.JndiDataSourceAutoConfiguration

      • org.springframework.boot.autoconfigure.jdbc.XADataSourceAutoConfiguration

        • 基于XA二階提交協(xié)議的分布式事務(wù)數(shù)據(jù)源
      • org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration

        • 支持事務(wù)
    • 具有的底層能力:數(shù)據(jù)源、JdbcTemplate事務(wù)

  • MyBatisAutoConfiguration:配置了MyBatis的整合流程

    • mybatis-spring-boot-starter導(dǎo)入 mybatis-spring-boot-autoconfigure(mybatis的自動(dòng)配置包),

    • 默認(rèn)加載兩個(gè)自動(dòng)配置類:

      • org.mybatis.spring.boot.autoconfigure.MybatisLanguageDriverAutoConfiguration

      • org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration

        • 必須在數(shù)據(jù)源配置好之后才配置
        • 給容器中SqlSessionFactory組件。創(chuàng)建和數(shù)據(jù)庫(kù)的一次會(huì)話
        • 給容器中SqlSessionTemplate組件。操作數(shù)據(jù)庫(kù)
    • MyBatis的所有配置綁定在MybatisProperties

    • 每個(gè)Mapper接口代理對(duì)象是怎么創(chuàng)建放到容器中。詳見**@MapperScan**原理:

      • 利用@Import(MapperScannerRegistrar.class)批量給容器中注冊(cè)組件。解析指定的包路徑里面的每一個(gè)類,為每一個(gè)Mapper接口類,創(chuàng)建Bean定義信息,注冊(cè)到容器中。

如何分析哪個(gè)場(chǎng)景導(dǎo)入以后,開啟了哪些自動(dòng)配置類。

找:classpath:/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports文件中配置的所有值,就是要開啟的自動(dòng)配置類,但是每個(gè)類可能有條件注解,基于條件注解判斷哪個(gè)自動(dòng)配置類生效了。

快速定位生效的配置

#開啟調(diào)試模式,詳細(xì)打印開啟了哪些自動(dòng)配置
debug=true
# Positive(生效的自動(dòng)配置)  Negative(不生效的自動(dòng)配置)

3.擴(kuò)展:整合其他數(shù)據(jù)源

3.1 Druid 數(shù)據(jù)源

暫不支持 SpringBoot3

  • 導(dǎo)入druid-starter
  • 寫配置
  • 分析自動(dòng)配置了哪些東西,怎么用

Druid官網(wǎng)

#數(shù)據(jù)源基本配置
spring.datasource.url=jdbc:mysql://192.168.200.100:3306/demo
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource

# 配置StatFilter監(jiān)控
spring.datasource.druid.filter.stat.enabled=true
spring.datasource.druid.filter.stat.db-type=mysql
spring.datasource.druid.filter.stat.log-slow-sql=true
spring.datasource.druid.filter.stat.slow-sql-millis=2000
# 配置WallFilter防火墻
spring.datasource.druid.filter.wall.enabled=true
spring.datasource.druid.filter.wall.db-type=mysql
spring.datasource.druid.filter.wall.config.delete-allow=false
spring.datasource.druid.filter.wall.config.drop-table-allow=false
# 配置監(jiān)控頁,內(nèi)置監(jiān)控頁面的首頁是 /druid/index.html
spring.datasource.druid.stat-view-servlet.enabled=true
spring.datasource.druid.stat-view-servlet.login-username=admin
spring.datasource.druid.stat-view-servlet.login-password=admin
spring.datasource.druid.stat-view-servlet.allow=*

# 其他 Filter 配置不再演示
# 目前為以下 Filter 提供了配置支持,請(qǐng)參考文檔或者根據(jù)IDE提示(spring.datasource.druid.filter.*)進(jìn)行配置。
# StatFilter
# WallFilter
# ConfigFilter
# EncodingConvertFilter
# Slf4jLogFilter
# Log4jFilter
# Log4j2Filter
# CommonsLogFilter

附錄:示例數(shù)據(jù)庫(kù)

CREATE DATABASE IF NOT EXISTS test;
USE test;
CREATE TABLE `t_user`
(
    `id`         BIGINT(20)   NOT NULL AUTO_INCREMENT COMMENT '編號(hào)',
    `login_name` VARCHAR(200) NULL DEFAULT NULL COMMENT '用戶名稱' COLLATE 'utf8_general_ci',
    `nick_name`  VARCHAR(200) NULL DEFAULT NULL COMMENT '用戶昵稱' COLLATE 'utf8_general_ci',
    `passwd`     VARCHAR(200) NULL DEFAULT NULL COMMENT '用戶密碼' COLLATE 'utf8_general_ci',
    PRIMARY KEY (`id`)
);
insert into t_user(login_name, nick_name, passwd) VALUES ('zhangsan','張三','123456');

SpringBoot3-基礎(chǔ)特性

1. SpringApplication

1.1 自定義 banner

  1. 類路徑添加banner.txt或設(shè)置spring.banner.location就可以定制 banner
    1. 推薦網(wǎng)站:Spring Boot banner 在線生成工具,制作下載英文 banner.txt,修改替換 banner.txt 文字實(shí)現(xiàn)自定義,個(gè)性化啟動(dòng) banner-bootschool.net

1.2.自定義 SpringApplication

import org.springframework.boot.Banner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class MyApplication {

    public static void main(String[] args) {
        //1.SpringApplication:Boot應(yīng)用的核心API入口
        //SpringApplication.run(Boot306FeaturesApplication.class,args);
        
        //1.自定義SpringApplication的底層設(shè)置
        SpringApplication application = new SpringApplication(MyApplication.class);
        //程序化調(diào)整SpringApplication的參數(shù)
        //application.setDefaultProperties();
        //這個(gè)配置不優(yōu)先
        //2.調(diào)整SpringApplication的參數(shù)
        application.setBannerMode(Banner.Mode.OFF);
        //3.SpringApplication運(yùn)行起來
        application.run(args);
    }


1.3FluentBuilder API

流式方式啟動(dòng)SpringApplication

new SpringApplicationBuilder()
    .sources(Parent.class)
    .child(Application.class)
    .bannerMode(Banner.Mode.OFF)
    .run(args);

2.Profiles

環(huán)境隔離能力;快速切換開發(fā)、測(cè)試、生產(chǎn)環(huán)境

步驟:

  1. 標(biāo)識(shí)環(huán)境:指定哪些組件、配置在哪個(gè)環(huán)境生效
  2. 切換環(huán)境:這個(gè)環(huán)境對(duì)應(yīng)的所有組件和配置就應(yīng)該生效

2.1 使用

2.1.1 指定環(huán)境

  • Spring Profiles 提供一種隔離配置的方式,使其僅在特定環(huán)境生效;
  • 任何@Component, @Configuration@ConfigurationProperties 可以使用 @Profile 標(biāo)記,來指定何時(shí)被加載?!?strong>容器中的組件都可以被 @Profile標(biāo)記】

2.1.2 環(huán)境激活

1.配置激活指定環(huán)境; 配置文件

spring.profiles.active=production,hsqldb

2.也可以使用命令行激活。--spring.profiles.active=dev,hsqldb

3.還可以配置默認(rèn)環(huán)境; 不標(biāo)注@Profile 的組件永遠(yuǎn)都存在。

  1. 以前默認(rèn)環(huán)境叫default
  2. spring.profiles.default=test

4.推薦使用激活方式激活指定環(huán)境

2.1.3 環(huán)境包含

注意:

  1. spring.profiles.activespring.profiles.default 只能用到 無 profile 的文件中,如果在application-dev.yaml中編寫就是無效的
  2. 也可以額外添加生效文件,而不是激活替換。比如:
spring.profiles.include[0]=common
spring.profiles.include[1]=local

最佳實(shí)戰(zhàn):

  • 生效的環(huán)境 = 激活的環(huán)境/默認(rèn)環(huán)境 + 包含的環(huán)境

  • 項(xiàng)目里面這么用

    • 基礎(chǔ)的配置mybatis、logxxx:寫到包含環(huán)境中
    • 需要?jiǎng)討B(tài)切換變化的 db、redis:寫到激活的環(huán)境中

2.2 Profile 分組

創(chuàng)建prod組,指定包含dbmq配置

spring.profiles.group.prod[0]=db
spring.profiles.group.prod[1]=mq

使用--spring.profiles.active=prod ,就會(huì)激活proddb,mq配置文件

2.3Profile 配置文件

  • application-{profile}.properties可以作為指定環(huán)境的配置文件。

  • 激活這個(gè)環(huán)境,配置就會(huì)生效。最終生效的所有配置

    • application.properties:主配置文件,任意時(shí)候都生效
    • application-{profile}.properties:指定環(huán)境配置文件,激活指定環(huán)境生效

如果發(fā)生配置沖突:profile優(yōu)先級(jí) > application

3.外部化配置

場(chǎng)景:線上應(yīng)用如何快速修改配置,并應(yīng)用最新配置?

  • SpringBoot 使用 配置優(yōu)先級(jí) + 外部配置 簡(jiǎn)化配置更新、簡(jiǎn)化運(yùn)維。
  • 只需要給jar應(yīng)用所在的文件夾放一個(gè)application.properties最新配置文件,重啟項(xiàng)目就能自動(dòng)應(yīng)用最新配置

3.1 配置優(yōu)先級(jí)

Spring Boot 允許將配置外部化,以便可以在不同的環(huán)境中使用相同的應(yīng)用程序代碼。

我們可以使用各種外部配置源,包括Java Properties文件、YAML文件、環(huán)境變量和命令行參數(shù)。

@Value可以獲取值,也可以用@ConfigurationProperties將所有屬性綁定到j(luò)ava object中

以下是 SpringBoot 屬性源加載順序。 后面的會(huì)覆蓋前面的值。由低到高,高優(yōu)先級(jí)配置覆蓋低優(yōu)先級(jí)

  1. 默認(rèn)屬性(通過SpringApplication.setDefaultProperties指定的)
  2. @PropertySource指定加載的配置(需要寫在@Configuration類上才可生效)
  3. 配置文件(application.properties/yml等)
  4. RandomValuePropertySource支持的random.*配置(如:@Value(“${random.int}”))
  5. OS 環(huán)境變量
  6. Java 系統(tǒng)屬性(System.getProperties()
  7. JNDI 屬性(來自java:comp/env
  8. ServletContext 初始化參數(shù)
  9. ServletConfig 初始化參數(shù)
  10. SPRING_APPLICATION_JSON屬性(內(nèi)置在環(huán)境變量或系統(tǒng)屬性中的 JSON)
  11. 命令行參數(shù)
  12. 測(cè)試屬性。(@SpringBootTest進(jìn)行測(cè)試時(shí)指定的屬性)
  13. 測(cè)試類@TestPropertySource注解
  14. Devtools 設(shè)置的全局屬性。($HOME/.config/spring-boot)

結(jié)論:配置可以寫到很多位置,常見的優(yōu)先級(jí)順序:

  • 命令行> 配置文件> springapplication配置

配置文件優(yōu)先級(jí)如下:(后面覆蓋前面)

  1. jar 包內(nèi)application.properties/yml
  2. jar 包內(nèi)application-{profile}.properties/yml
  3. jar 包外application.properties/yml
  4. jar 包外application-{profile}.properties/yml

建議用一種格式的配置文件。如果.properties和.yml同時(shí)存在,則.properties優(yōu)先

結(jié)論:包外 > 包內(nèi); 同級(jí)情況:profile配置 > application配置

所有參數(shù)均可由命令行傳入,使用--參數(shù)項(xiàng)=參數(shù)值,將會(huì)被添加到環(huán)境變量中,并優(yōu)先于配置文件

比如java -jar app.jar --name="Spring",可以使用@Value("${name}")獲取

演示場(chǎng)景:

  • 包內(nèi): application.properties server.port=8000
  • 包內(nèi): application-dev.properties server.port=9000
  • 包外: application.properties server.port=8001
  • 包外: application-dev.properties server.port=9001

啟動(dòng)端口?:命令行 > 9001 > 8001 > 9000 > 8000

3.2. 外部配置

SpringBoot 應(yīng)用啟動(dòng)時(shí)會(huì)自動(dòng)尋找application.properties和application.yaml位置,進(jìn)行加載。順序如下:(后面覆蓋前面

1.類路徑: 內(nèi)部

  1. 類根路徑
  2. 類下/config包

2.當(dāng)前路徑(項(xiàng)目所在的位置)

  1. 當(dāng)前路徑
  2. 當(dāng)前下/config子目錄
  3. /config目錄的直接子目錄

最終效果:優(yōu)先級(jí)由高到低,前面覆蓋后面

  • 命令行 > 包外config直接子目錄 > 包外config目錄 > 包外根目錄 > 包內(nèi)目錄

  • 同級(jí)比較:

    • profile配置 > 默認(rèn)配置
    • properties配置 > yaml配置

【SpringBoot3】--03.數(shù)據(jù)訪問、基礎(chǔ)特性(外部化和內(nèi)部外配置、整合JUnit),Java,spring boot,junit,java

規(guī)律:最外層的最優(yōu)先。

  • 命令行 > 所有
  • 包外 > 包內(nèi)
  • config目錄 > 根目錄
  • profile > application

配置不同就都生效(互補(bǔ)),配置相同高優(yōu)先級(jí)覆蓋低優(yōu)先級(jí)

3.3. 導(dǎo)入配置

使用spring.config.import可以導(dǎo)入額外配置

spring.config.import=my.properties
my.property=value

無論以上寫法的先后順序,my.properties的值總是優(yōu)先于直接在文件中編寫的my.property。

3.4. 屬性占位符

配置文件中可以使用 ${name:default}形式取出之前配置過的值。

app.name=MyApp
app.description=${app.name} is a Spring Boot application written by ${username:Unknown}

4. 單元測(cè)試-JUnit5

4.1 整合

SpringBoot 提供一系列測(cè)試工具集及注解方便我們進(jìn)行測(cè)試。

spring-boot-test提供核心測(cè)試能力,spring-boot-test-autoconfigure 提供測(cè)試的一些自動(dòng)配置。

我們只需要導(dǎo)入spring-boot-starter-test 即可整合測(cè)試

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

spring-boot-starter-test 默認(rèn)提供了以下庫(kù)供我們測(cè)試使用

  • JUnit 5
  • Spring Test
  • AssertJ
  • Hamcrest
  • Mockito
  • JSONassert
  • JsonPath

4.2測(cè)試

4.2.0 組件測(cè)試

直接@Autowired容器中的組件進(jìn)行測(cè)試

4.2.1 注解

JUnit5的注解與JUnit4的注解有所變化

https://junit.org/junit5/docs/current/user-guide/#writing-tests-annotations

  • @Test:表示方法是測(cè)試方法。但是與JUnit4的@Test不同,他的職責(zé)非常單一不能聲明任何屬性,拓展的測(cè)試將會(huì)由Jupiter提供額外測(cè)試
  • @ParameterizedTest:表示方法是參數(shù)化測(cè)試,下方會(huì)有詳細(xì)介紹
  • @RepeatedTest:表示方法可重復(fù)執(zhí)行,下方會(huì)有詳細(xì)介紹
  • @DisplayName:為測(cè)試類或者測(cè)試方法設(shè)置展示名稱
  • @BeforeEach:表示在每個(gè)單元測(cè)試之前執(zhí)行
  • @AfterEach:表示在每個(gè)單元測(cè)試之后執(zhí)行
  • @BeforeAll:表示在所有單元測(cè)試之前執(zhí)行
  • @AfterAll:表示在所有單元測(cè)試之后執(zhí)行
  • @Tag:表示單元測(cè)試類別,類似于JUnit4中的@Categories
  • @Disabled:表示測(cè)試類或測(cè)試方法不執(zhí)行,類似于JUnit4中的@Ignore
  • @Timeout:表示測(cè)試方法運(yùn)行如果超過了指定時(shí)間將會(huì)返回錯(cuò)誤
  • @ExtendWith:為測(cè)試類或測(cè)試方法提供擴(kuò)展類引用
import static org.junit.jupiter.api.Assertions.fail;
import static org.junit.jupiter.api.Assumptions.assumeTrue;

import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;

class StandardTests {

    @BeforeAll
    static void initAll() {
    }

    @BeforeEach
    void init() {
    }

    @DisplayName("??")
    @Test
    void succeedingTest() {
    }

    @Test
    void failingTest() {
        fail("a failing test");
    }

    @Test
    @Disabled("for demonstration purposes")
    void skippedTest() {
        // not executed
    }

    @Test
    void abortedTest() {
        assumeTrue("abc".contains("Z"));
        fail("test should have been aborted");
    }

    @AfterEach
    void tearDown() {
    }

    @AfterAll
    static void tearDownAll() {
    }

}

4.2.2 斷言

方法 說明
assertEquals 判斷兩個(gè)對(duì)象或兩個(gè)原始類型是否相等
assertNotEquals 判斷兩個(gè)對(duì)象或兩個(gè)原始類型是否不相等
assertSame 判斷兩個(gè)對(duì)象引用是否指向同一個(gè)對(duì)象
assertNotSame 判斷兩個(gè)對(duì)象引用是否指向不同的對(duì)象
assertTrue 判斷給定的布爾值是否為 true
assertFalse 判斷給定的布爾值是否為 false
assertNull 判斷給定的對(duì)象引用是否為 null
assertNotNull 判斷給定的對(duì)象引用是否不為 null
assertArrayEquals 數(shù)組斷言
assertAll 組合斷言
assertThrows 異常斷言
assertTimeout 超時(shí)斷言
fail 快速失敗

4.2.3 嵌套測(cè)試

JUnit 5 可以通過 Java 中的內(nèi)部類和@Nested 注解實(shí)現(xiàn)嵌套測(cè)試,從而可以更好的把相關(guān)的測(cè)試方法組織在一起。在內(nèi)部類中可以使用@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());
            }
        }
    }
}

4.2.4 參數(shù)化測(cè)試

參數(shù)化測(cè)試是JUnit5很重要的一個(gè)新特性,它使得用不同的參數(shù)多次運(yùn)行測(cè)試成為了可能,也為我們的單元測(cè)試帶來許多便利。

利用@ValueSource等注解,指定入?yún)ⅲ覀儗⒖梢允褂貌煌膮?shù)進(jìn)行多次單元測(cè)試,而不需要每新增一個(gè)參數(shù)就新增一個(gè)單元測(cè)試,省去了很多冗余代碼。

@ValueSource: 為參數(shù)化測(cè)試指定入?yún)碓?,支持八大基礎(chǔ)類以及String類型,Class類型
@NullSource: 表示為參數(shù)化測(cè)試提供一個(gè)null的入?yún)?br>@EnumSource: 表示為參數(shù)化測(cè)試提供一個(gè)枚舉入?yún)?br>@CsvFileSource:表示讀取指定CSV文件內(nèi)容作為參數(shù)化測(cè)試入?yún)?br>@MethodSource:表示讀取指定方法的返回值作為參數(shù)化測(cè)試入?yún)?注意方法返回需要是一個(gè)流)文章來源地址http://www.zghlxwxcb.cn/news/detail-574259.html

@ParameterizedTest
@ValueSource(strings = {"one", "two", "three"})
@DisplayName("參數(shù)化測(cè)試1")
public void parameterizedTest1(String string) {
    System.out.println(string);
    Assertions.assertTrue(StringUtils.isNotBlank(string));
}


@ParameterizedTest
@MethodSource("method")    //指定方法名
@DisplayName("方法來源參數(shù)")
public void testWithExplicitLocalMethodSource(String name) {
    System.out.println(name);
    Assertions.assertNotNull(name);
}

static Stream<String> method() {
    return Stream.of("apple", "banana");
}

到了這里,關(guān)于【SpringBoot3】--03.數(shù)據(jù)訪問、基礎(chǔ)特性(外部化和內(nèi)部外配置、整合JUnit)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點(diǎn)僅代表作者本人,不代表本站立場(chǎng)。本站僅提供信息存儲(chǔ)空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請(qǐng)注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實(shí)不符,請(qǐng)點(diǎn)擊違法舉報(bào)進(jìn)行投訴反饋,一經(jīng)查實(shí),立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費(fèi)用

相關(guān)文章

  • SpringBoot3 CORS跨域訪問

    SpringBoot3 CORS跨域訪問

    目錄 Credentials ?編輯 問題一 問題二 問題三 解決方法一 CrossOrigin,最優(yōu)的方法 ?解決方法二 通過Filter 設(shè)置HTTP 解決方法三 通過實(shí)現(xiàn)WebMvcConfigurer設(shè)置HTTP 解決方法四 通過CorsFilter Access-Control-Allow-Headers?authorization 問題 解決辦法,服務(wù)器添加authorization HTTP 協(xié)議,需要認(rèn)真的學(xué)

    2024年02月07日
    瀏覽(16)
  • Springboot3新特性:GraalVM Native Image Support和虛擬線程(從入門到精通)

    Springboot3新特性:GraalVM Native Image Support和虛擬線程(從入門到精通)

    說明 :都知道,我是搞java的,最近搞c的算法和redis數(shù)據(jù)庫(kù)比較多,所以對(duì)于以下文章,都是我自己這樣認(rèn)為的,各位看完之后,可盡情評(píng)論。 以往文章: Springboot3新特性:開發(fā)第一個(gè) GraalVM 本機(jī)應(yīng)用程序(完整教程)-CSDN博客 利用GraalVM將java文件變成exe可執(zhí)行文件-CSDN博客 概述

    2024年01月16日
    瀏覽(54)
  • SpringBoot外部化配置

    SpringBoot外部化配置

    Spring Boot允許外部化項(xiàng)目配置,以便您可以在不同的環(huán)境中使用相同的應(yīng)用程序代碼。您可以使用各種外部配置源,包括Java屬性文件、YAML文件、環(huán)境變量和命令行參數(shù)。 屬性值可以通過使用@Value注釋直接注入到bean中,通過Spring的環(huán)境抽象進(jìn)行訪問,或者通過@ConfigurationProp

    2024年03月09日
    瀏覽(15)
  • SpringBoot3基礎(chǔ)用法

    SpringBoot3基礎(chǔ)用法

    目錄 一、背景 二、環(huán)境搭建 1、工程結(jié)構(gòu) 2、框架依賴 3、環(huán)境配置 三、入門案例 1、測(cè)試接口 2、全局異常 3、日志打印 3.1 日志配置 3.2 日志打印 四、打包運(yùn)行 五、參考源碼 技術(shù)和工具「!喜新厭舊」 最近在一個(gè)輕量級(jí)的服務(wù)中,嘗試了最新的技術(shù)和工具選型; 即 SpringB

    2024年02月14日
    瀏覽(16)
  • 1. SpringBoot3 基礎(chǔ)

    1. SpringBoot3 基礎(chǔ)

    在 SpringBoot 之前,通過 Spring Framework 整合各種子項(xiàng)目,來構(gòu)建 Spring應(yīng)用程序: 傳統(tǒng)方式構(gòu)建 spring 應(yīng)用程序,需要挨個(gè)導(dǎo)入依賴,項(xiàng)目配置繁瑣: SpringBoot 是 Spring 提供的一個(gè)子項(xiàng)目,用于快速構(gòu)建 Spring 應(yīng)用程序: SpringBoot 的特性,用于簡(jiǎn)化開發(fā): (1) 起步依賴 :本質(zhì)上就

    2024年01月20日
    瀏覽(19)
  • SpringBoot3.0新特性:1、spring.factories文件廢棄,自動(dòng)配置包位置變化 2、Spring Native 快速體驗(yàn) 3、jakata api遷移 3、三方庫(kù)的支持

    SpringBoot3.0新特性:1、spring.factories文件廢棄,自動(dòng)配置包位置變化 2、Spring Native 快速體驗(yàn) 3、jakata api遷移 3、三方庫(kù)的支持

    有自己寫過starter包的友友們一定知道,一定用/META-INF/spring.factories文件定義發(fā)現(xiàn)自動(dòng)配置,但是在springboot 2.7,這個(gè)文件就被棄用了,在springboot 3.0 就被徹底移除了。 比如之前定義的/META-INF/spring.factories文件: 而現(xiàn)在 這個(gè)/META-INF/spring.factories并不是不存在了,只是在3.0之后 外

    2024年02月10日
    瀏覽(22)
  • SpringBoot3數(shù)據(jù)庫(kù)集成

    SpringBoot3數(shù)據(jù)庫(kù)集成

    標(biāo)簽:Jdbc.Druid.Mybatis.Plus; 項(xiàng)目工程中,集成數(shù)據(jù)庫(kù)實(shí)現(xiàn)對(duì)數(shù)據(jù)的增曬改查管理,是最基礎(chǔ)的能力,而對(duì)于這個(gè)功能的實(shí)現(xiàn),其組件選型也非常豐富; 通過如下幾個(gè)組件來實(shí)現(xiàn)數(shù)據(jù)庫(kù)的整合; Druid連接池 :阿里開源的數(shù)據(jù)庫(kù)連接池,并且提供 SQL 執(zhí)行的監(jiān)控能力; MybatisPlu

    2024年02月13日
    瀏覽(28)
  • 【Docker】RocketMQ5.1.0的配置部署與基于SpringBoot3.0.5的代碼基礎(chǔ)配置

    【Docker】RocketMQ5.1.0的配置部署與基于SpringBoot3.0.5的代碼基礎(chǔ)配置

    JAVA 17 SpringBoot 3.0.5 CentOS 7.5 Rocket 5.1.0 1.1 查看鏡像 1.2 拉取鏡像 1.3 查看已拉取鏡像 1.4 創(chuàng)建掛載文件夾 1.4.1 創(chuàng)建Broker掛載文件夾 1.4.2 創(chuàng)建NameServer掛載文件夾 1.5 啟動(dòng)容器以復(fù)制配置文件 1.5.1 啟動(dòng)NamerServer容器 1.5.2 復(fù)制NameServer啟動(dòng)腳本 1.5.3 修改腳本文件 1.5.4 停止并刪除Name

    2024年02月12日
    瀏覽(30)
  • SpringBoot3整合Druid數(shù)據(jù)源的解決方案

    SpringBoot3整合Druid數(shù)據(jù)源的解決方案

    druid-spring-boot-3-starter目前最新版本是1.2.20,雖然適配了SpringBoot3,但缺少自動(dòng)裝配的配置文件,會(huì)導(dǎo)致加載時(shí)報(bào)加載驅(qū)動(dòng)異常。 需要手動(dòng)在resources目錄下創(chuàng)建 META-INF/spring/ 目錄,并且在 META-INF/spring/ 創(chuàng)建 org.springframework.boot.autoconfigure.AutoConfiguration.imports , 文件中添加如下內(nèi)容

    2024年03月09日
    瀏覽(39)
  • ES基礎(chǔ)、高級(jí)特性及整合SpringBoot

    ES基礎(chǔ)、高級(jí)特性及整合SpringBoot

    ? ? ? ? 之前給服務(wù)器安好了ES和Kibana一直沒來得及動(dòng)手試試,這篇就系統(tǒng)性地介紹一下ES的基本使用和特性,以及如何將其與SpringBoot整合。 ????????本文基于 ElasticSearch 7.5.0 + Kibana 7.5.0,版本一定要一致! 目錄 1 什么是ElasticSearch? 2 ElasticSearch基本概念 2.1 ElasticSearch/Ki

    2024年02月05日
    瀏覽(15)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請(qǐng)作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包