mirror of
https://github.com/Estom/notes.git
synced 2026-11-27 22:01:41 +08:00
java & sofabolt
This commit is contained in:
@@ -5,7 +5,7 @@
|
||||
> * 原生配置文件,xml定义的配置文件
|
||||
> * 属性配置文件:spring配置key-value的文件
|
||||
|
||||
## 1 properties配置基础
|
||||
## 1 properties配置文件
|
||||
|
||||
### properties默认配置文件
|
||||
用于配置容器端口名、数据库链接信息、日志级别。pom是项目编程的配置,properties是软件部署的配置。
|
||||
@@ -92,6 +92,55 @@ com.didispace.blog.test2=${random.int[10,20]}
|
||||
```
|
||||
|
||||
|
||||
### 读取规则
|
||||
|
||||
将配置文件中的值引入到java程序中。
|
||||
|
||||
在Spring应用程序的environment中读取属性的时候,每个属性的唯一名称符合如下规则:
|
||||
|
||||
* 通过.分离各个元素
|
||||
* 最后一个.将前缀与属性名称分开
|
||||
* 必须是字母(a-z)和数字(0-9)
|
||||
* 必须是小写字母
|
||||
* 用连字符-来分隔单词
|
||||
* 唯一允许的其他字符是[和],用于List的索引
|
||||
* 不能以数字开头
|
||||
|
||||
```
|
||||
this.environment.containsProperty("spring.jpa.database-platform")
|
||||
```
|
||||
|
||||
### 配置提示
|
||||
|
||||
引入配置提示的依赖。并在maven插件中,将该依赖排除。
|
||||
|
||||
```xml
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-configuration-processor</artifactId>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<configuration>
|
||||
<excludes>
|
||||
<exclude>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-configuration-processor</artifactId>
|
||||
</exclude>
|
||||
</excludes>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
```
|
||||
|
||||
|
||||
## 2 yaml配置文件
|
||||
### yaml基本语法
|
||||
|
||||
@@ -137,7 +186,7 @@ k:
|
||||
```
|
||||
|
||||
### yaml的实例
|
||||
```
|
||||
```java
|
||||
@Data
|
||||
public class Person {
|
||||
|
||||
@@ -195,6 +244,13 @@ person:
|
||||
## 3 其他配置方式
|
||||
### 系统环境变量
|
||||
|
||||
java程序启动参数 -D是用来做什么:
|
||||
Set a system property value. If value is a string that contains spaces, you must enclose the string in double quotes。在运行改程序时加上JVM参数-Ddubbo.token=“666” 或者 -Ddubbo.token=666,那么运行之后你可以看到控制台输出了666!一点值得注意的是,需要设置的是JVM参数而不是program参数
|
||||
|
||||
```
|
||||
java -Dfoo="some string" SomeClass
|
||||
```
|
||||
|
||||
* 列表形式:由于环境变量中无法使用[和]符号,所以使用_来替代。任何由下划线包围的数字都会被认为是[]的数组形式。
|
||||
```
|
||||
MY_FOO_1_ = my.foo[1]
|
||||
@@ -219,7 +275,7 @@ java -jar xxx.jar --server.port=8888
|
||||
|
||||
## 4 多环境配置
|
||||
|
||||
### 配置方法
|
||||
### 多环境配置文件
|
||||
对于多环境的配置,各种项目构建工具或是框架的基本思路是一致的,通过配置多份不同环境的配置文件,再通过打包命令指定需要打包的内容之后进行区分打包。
|
||||
|
||||
在Spring Boot中多环境配置文件名需要满足application-{profile}.properties的格式,其中{profile}对应你的环境标识,比如:
|
||||
@@ -228,20 +284,67 @@ java -jar xxx.jar --server.port=8888
|
||||
* application-test.properties:测试环境
|
||||
* application-prod.properties:生产环境
|
||||
|
||||
|
||||
### 多配置文件的加载规则
|
||||
application.yml/properties总是会被加载,不管是否配置spring.profile.active.
|
||||
|
||||
|
||||
1. 配置文件的方式。在默认配置文件中application.properties指定环境。最先加载application.yml/properties,然后再按照spring.profile.active加载相应的application-{profile}.yml(properties)。如果application和application-{profile}中键有重复会被application-{profile}替换为最新的。
|
||||
2. Java系统属性方式。在启动jar时指定加载配置(Java系统属性方式)或者通过java代码设置系统属性的方式。
|
||||
```java
|
||||
// -Dspring.profiles.active=mydev123一定要放-jar之前能触发java属性方式
|
||||
java -Dspring.profiles.active=mydev123 -jar SpringBootEnv-1.0.jar
|
||||
|
||||
// 通过java代码设置系统属性的方式。
|
||||
System.setProperty("spring.profiles.active","mydev");
|
||||
```
|
||||
3. 命令行的方式。在启动jar时指定加载配置(命令行方式)
|
||||
```shell
|
||||
java -jar SpringBootEnv-1.0.jar --spring.profiles.active=dev56789
|
||||
```
|
||||
4. 系统环境变量的方式。在启动jar时指定加载配置(系统环境变量方式)。首先增加一个名称为SPRING_PROFILES_ACTIVE的系统环境变量,启动spring程序。
|
||||
|
||||
```shell
|
||||
#当前系统是windows
|
||||
set SPRING_PROFILES_ACTIVE=dev987
|
||||
java -jar SpringBootEnv-1.0.jar
|
||||
```
|
||||
|
||||
以上四种方式的优先级
|
||||
```
|
||||
命令行方式 > Java系统属性方式 > 系统环境变量方式 > 配置文件方式
|
||||
```
|
||||
如果需要激活多个profile可以使用逗号隔开,
|
||||
```
|
||||
spring.profiles.active=dev,test
|
||||
```
|
||||
|
||||
|
||||
### 配置加载顺序
|
||||
|
||||
SpringBoot启动会扫描以下位置的application.properties/yml文件作为spring boot的默认配置文件:
|
||||
|
||||
```
|
||||
#file: 指当前项目根目录
|
||||
file:./config/
|
||||
file:./
|
||||
#classpath: 指当前项目的resources目录
|
||||
classpath:/config/
|
||||
classpath:
|
||||
```
|
||||
|
||||
1. 命令行中传入的参数。
|
||||
1. SPRING_APPLICATION_JSON中的属性。SPRING_APPLICATION_JSON是以JSON格式配置在系统环境变量中的内容。
|
||||
1. java:comp/env中的JNDI属性。
|
||||
1. Java的系统属性,可以通过System.getProperties()获得的内容。
|
||||
1. 操作系统的环境变量
|
||||
1. 通过random.*配置的随机属性
|
||||
1. 位于当前应用jar包之外,针对不同{profile}环境的配置文件内容,例如:application-{profile}.properties或是YAML定义的配置文件
|
||||
1. 位于当前应用jar包之内,针对不同{profile}环境的配置文件内容,例如:application-{profile}.properties或是YAML定义的配置文件
|
||||
1. 位于当前应用jar包之外的application.properties和YAML配置内容
|
||||
1. 位于当前应用jar包之内的application.properties和YAML配置内容
|
||||
1. 在@Configuration注解修改的类中,通过@PropertySource注解定义的属性
|
||||
1. 应用默认属性,使用SpringApplication.setDefaultProperties定义的内容1.
|
||||
2. SPRING_APPLICATION_JSON中的属性。SPRING_APPLICATION_JSON是以JSON格式配置在系统环境变量中的内容。
|
||||
3. java:comp/env中的JNDI属性。
|
||||
4. Java的系统属性,可以通过System.getProperties()获得的内容。
|
||||
5. 操作系统的环境变量
|
||||
6. 通过random.*配置的随机属性
|
||||
7. 位于当前应用jar包之外,针对不同{profile}环境的配置文件内容,例如:application-{profile}.properties或是YAML定义的配置文件
|
||||
8. 位于当前应用jar包之内,针对不同{profile}环境的配置文件内容,例如:application-{profile}.properties或是YAML定义的配置文件
|
||||
9. 位于当前应用jar包之外的application.properties和YAML配置内容
|
||||
10. 位于当前应用jar包之内的application.properties和YAML配置内容
|
||||
11. 在@Configuration注解修改的类中,通过@PropertySource注解定义的属性
|
||||
12. 应用默认属性,使用SpringApplication.setDefaultProperties定义的内容1.
|
||||
|
||||
## 5 配置绑定
|
||||
### 使用Java程序读取
|
||||
@@ -261,53 +364,6 @@ public class getProperties {
|
||||
}
|
||||
}
|
||||
```
|
||||
### 读取规则
|
||||
|
||||
将配置文件中的值引入到java程序中。
|
||||
|
||||
在Spring应用程序的environment中读取属性的时候,每个属性的唯一名称符合如下规则:
|
||||
|
||||
* 通过.分离各个元素
|
||||
* 最后一个.将前缀与属性名称分开
|
||||
* 必须是字母(a-z)和数字(0-9)
|
||||
* 必须是小写字母
|
||||
* 用连字符-来分隔单词
|
||||
* 唯一允许的其他字符是[和],用于List的索引
|
||||
* 不能以数字开头
|
||||
|
||||
```
|
||||
this.environment.containsProperty("spring.jpa.database-platform")
|
||||
```
|
||||
|
||||
### 配置提示
|
||||
|
||||
引入配置提示的依赖。并在maven插件中,将该依赖排除。
|
||||
|
||||
```xml
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-configuration-processor</artifactId>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<configuration>
|
||||
<excludes>
|
||||
<exclude>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-configuration-processor</artifactId>
|
||||
</exclude>
|
||||
</excludes>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
```
|
||||
|
||||
|
||||
### @ConfigurationProperties+Componet
|
||||
@@ -347,7 +403,7 @@ public class Application {
|
||||
```
|
||||
|
||||
|
||||
### @Configuration+ @EnableConfigurationProperties
|
||||
### @ConfigurationProperties+ @EnableConfigurationProperties
|
||||
|
||||
1. 在配置类上开启属性配置功能。开启car的属性配置功能
|
||||
2. 该中方法对配置类进行修改然后装配。不需要修改类本身的代码。
|
||||
@@ -372,22 +428,157 @@ public class FooProperties {
|
||||
|
||||
|
||||
### @Value
|
||||
* 通过占位符的方式加载自定义的参数
|
||||
通过占位符的方式加载自定义的参数
|
||||
|
||||
```
|
||||
@Component
|
||||
public class Book {
|
||||
* 注入普通字符;
|
||||
* 注入操作系统属性;
|
||||
* 注入表达式运算结果;
|
||||
* 注入其他Bean的属性;
|
||||
* 注入文件内容;
|
||||
* 注入网址内容;
|
||||
* 注入属性文件。
|
||||
|
||||
@Value("${book.name}")
|
||||
private String name;
|
||||
@Value("${book.author}")
|
||||
private String author;
|
||||
```java
|
||||
|
||||
// 省略getter和setter
|
||||
/**
|
||||
* 配置类
|
||||
**/
|
||||
@Configuration
|
||||
@ComponentScan("com.kongzi")
|
||||
@PropertySource("classpath:db.properties")
|
||||
public class ElConfig
|
||||
{
|
||||
/**
|
||||
* 注入普通字符串
|
||||
*/
|
||||
@Value("您好,欢迎访问 carefree 的博客")
|
||||
private String comment;
|
||||
|
||||
/**
|
||||
* 注入操作系统属性
|
||||
*/
|
||||
@Value("#{systemProperties['os.name']}")
|
||||
private String osName;
|
||||
|
||||
/**
|
||||
* 注入表达式运算结果
|
||||
*/
|
||||
@Value("#{ T(java.lang.Math).random() * 100.0 }")
|
||||
private double randomNumber;
|
||||
|
||||
/**
|
||||
* 注入其他Bean的属性
|
||||
*/
|
||||
@Value("#{otherUser.userName}")
|
||||
private String fromUserName;
|
||||
|
||||
@Value("#{otherUser.blogUrl}")
|
||||
private String fromBlogUrl;
|
||||
|
||||
/**
|
||||
* 注入文件资源
|
||||
*/
|
||||
@Value("classpath:info.txt")
|
||||
private Resource testFile;
|
||||
|
||||
/**
|
||||
* 注入网址资源
|
||||
*/
|
||||
@Value("https://blog.csdn.net/carefree31441")
|
||||
private Resource testUrl;
|
||||
|
||||
/**
|
||||
* 注入配置文件
|
||||
*/
|
||||
@Value("${jdbc.driver}")
|
||||
private String jdbc_driver;
|
||||
|
||||
@Value("${jdbc.url}")
|
||||
private String jdbc_url;
|
||||
|
||||
@Value("${jdbc.username}")
|
||||
private String jdbc_username;
|
||||
|
||||
@Value("${jdbc.password}")
|
||||
private String jdbc_password;
|
||||
|
||||
@Autowired
|
||||
private Environment environment;
|
||||
|
||||
@Bean
|
||||
public static PropertySourcesPlaceholderConfigurer propertyConfigurer()
|
||||
{
|
||||
return new PropertySourcesPlaceholderConfigurer();
|
||||
}
|
||||
|
||||
public void outputResource()
|
||||
{
|
||||
try
|
||||
{
|
||||
System.out.println("注入普通字符串:");
|
||||
System.out.println(comment);
|
||||
System.out.println("------------------------------------------------");
|
||||
|
||||
System.out.println("注入操作系统属性:");
|
||||
System.out.println(osName);
|
||||
System.out.println("------------------------------------------------");
|
||||
|
||||
System.out.println("注入表达式运算结果:");
|
||||
System.out.println(randomNumber);
|
||||
System.out.println("------------------------------------------------");
|
||||
|
||||
System.out.println("注入其他Bean的属性:");
|
||||
System.out.println("用户名称:" + fromUserName);
|
||||
System.out.println("博客地址:"+ fromBlogUrl);
|
||||
System.out.println("------------------------------------------------");
|
||||
|
||||
System.out.println("注入文件资源:");
|
||||
System.out.println("文件中的内容:" + IOUtils.toString(testFile.getInputStream()));
|
||||
System.out.println("------------------------------------------------");
|
||||
|
||||
System.out.println("注入配置文件(方式一):");
|
||||
System.out.println("数据库驱动:" + jdbc_driver);
|
||||
System.out.println("数据库连接:" + jdbc_url);
|
||||
System.out.println("数据库用户:" + jdbc_username);
|
||||
System.out.println("数据库密码:" + jdbc_password);
|
||||
System.out.println("------------------------------------------------");
|
||||
|
||||
System.out.println("注入配置文件(方式二):");
|
||||
System.out.println("数据库驱动:" + environment.getProperty("jdbc.driver"));
|
||||
System.out.println("数据库连接:" + environment.getProperty("jdbc.url"));
|
||||
System.out.println("数据库用户:" + environment.getProperty("jdbc.username"));
|
||||
System.out.println("数据库密码:" + environment.getProperty("jdbc.password"));
|
||||
System.out.println("------------------------------------------------");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
ex.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
* @Value支持的表达式格式
|
||||
|
||||
### @PropertySource注解加载properties文件
|
||||
PropertySource注解的作用是加载指定的属性文件,配置属性如下
|
||||
```
|
||||
#{...}
|
||||
${...}
|
||||
@PropertySource(value= {"classpath:config/mail.properties"},ignoreResourceNotFound=false,encoding="UTF-8",name="mail.properties")
|
||||
```
|
||||
* 其中value是设置需要加载的属性文件,可以一次性加载多个(多个时以,分隔);
|
||||
* encoding用于指定读取属性文件所使用的编码,我们通常使用的是UTF-8;
|
||||
* ignoreResourceNotFound含义是当指定的配置文件不存在是否报错,默认是false;如这里配置的config/mail.properties,若在classpath路径下不存在时,则ignoreResourceNotFound为true的时候,程序不会报错,如果ignoreResourceNotFound为false的时候,程序直接报错。实际项目开发中,最好设置ignoreResourceNotFound为false,该参数默认值为false。
|
||||
* name的值我们设置的是mail.properties。这个值在Springboot的环境中必须是唯一的,如果不设置,则值为:“class path resource [config/mail.properties]“。
|
||||
|
||||
|
||||
```java
|
||||
@Component
|
||||
@ConfigurationProperties(prefix = "mail")
|
||||
@PropertySource(value = "classpath:config/mail.properties",encoding = "UTF-8")
|
||||
public class MailConfig
|
||||
{
|
||||
private String host;
|
||||
|
||||
private String port;
|
||||
|
||||
//省略getter与setter方法...
|
||||
}
|
||||
```
|
||||
@@ -21,10 +21,10 @@
|
||||
@startuml
|
||||
|
||||
object HttpServlet{
|
||||
doGet()
|
||||
doPost()
|
||||
doPut()
|
||||
doDelete()
|
||||
doGet
|
||||
doPost
|
||||
doPut
|
||||
doDelete
|
||||
}
|
||||
note bottom : 这是所有http请求的入口。\
|
||||
\n 可以通过子类,不断丰富和具体要执行的内容。
|
||||
@@ -35,16 +35,16 @@ object HttpServletBean{
|
||||
}
|
||||
|
||||
object FrameworkServlet{
|
||||
doGet()--> processRequest()
|
||||
doPost()--> processRequest()
|
||||
doPut()--> processRequest()
|
||||
doDelete() --> processRequest()
|
||||
processRequest()-->doService()
|
||||
doGet--> processRequest
|
||||
doPost --> processRequest
|
||||
doPut --> processRequest
|
||||
doDelete --> processRequest
|
||||
processRequest -->doService
|
||||
}
|
||||
|
||||
object DispatcherServlet{
|
||||
doService()-->doDispatcher()
|
||||
doDispatcher()
|
||||
doService -->doDispatcher
|
||||
doDispatcher
|
||||
}
|
||||
|
||||
|
||||
|
||||
216
Spring/Springboot/springboot-test.md
Normal file
216
Spring/Springboot/springboot-test.md
Normal file
@@ -0,0 +1,216 @@
|
||||
|
||||
> springboot with junit4 &junit5 https://segmentfault.com/a/1190000040803747
|
||||
|
||||
## 1 概述
|
||||
### 多种测试模式
|
||||
|
||||
|
||||
* @RunWith(SpringJUnit4ClassRunner.class)启动Spring上下文环境。
|
||||
* @RunWith(MockitoJUnitRunner.class)mockito方法进行测试。对底层的类进行mock,测试速度快。
|
||||
* @RunWith(PowerMockRunner.class)powermock方法进行测试。对底层类进行mock,测试方法更全面。
|
||||
|
||||
### spring-boot-starter-test
|
||||
SpringBoot中有关测试的框架,主要来源于 spring-boot-starter-test。一旦依赖了spring-boot-starter-test,下面这些类库将被一同依赖进去:
|
||||
* JUnit:java测试事实上的标准。
|
||||
* Spring Test & Spring Boot Test:Spring的测试支持。
|
||||
* AssertJ:提供了流式的断言方式。
|
||||
* Hamcrest:提供了丰富的matcher。
|
||||
* Mockito:mock框架,可以按类型创建mock对象,可以根据方法参数指定特定的响应,也支持对于mock调用过程的断言。
|
||||
* JSONassert:为JSON提供了断言功能。
|
||||
* JsonPath:为JSON提供了XPATH功能。
|
||||
|
||||
|
||||
|
||||
### junit4 & junit5对比
|
||||
|
||||
|
||||
| 功能 | JUnit4 | JUnit5 |
|
||||
|------------------|--------------|--------------|
|
||||
| 声明一种测试方法 | @Test | @Test |
|
||||
| 在当前类中的所有测试方法之前执行 | @BeforeClass | @BeforeAll |
|
||||
| 在当前类中的所有测试方法之后执行 | @AfterClass | @AfterAll |
|
||||
| 在每个测试方法之前执行 | @Before | @BeforeEach |
|
||||
| 在每个测试方法之后执行 | @After | @AfterEach |
|
||||
| 禁用测试方法/类 | @Ignore | @Disabled |
|
||||
| 测试工厂进行动态测试 | NA | @TestFactory |
|
||||
| 嵌套测试 | NA | @Nested |
|
||||
| 标记和过滤 | @Category | @Tag |
|
||||
| 注册自定义扩展 | NA | @ExtendWith |
|
||||
|
||||
|
||||
### RunWith 和 ExtendWith
|
||||
|
||||
在 JUnit4 版本,在测试类加 @SpringBootTest 注解时,同样要加上 @RunWith(SpringRunner.class)才生效,即:
|
||||
```
|
||||
@SpringBootTest
|
||||
@RunWith(SpringRunner.class)
|
||||
class HrServiceTest {
|
||||
...
|
||||
}
|
||||
```
|
||||
但在 JUnit5 中,官网告知 @RunWith 的功能都被 @ExtendWith 替代,即原 @RunWith(SpringRunner.class) 被同功能的 @ExtendWith(SpringExtension.class) 替代。但 JUnit5 中 @SpringBootTest 注解中已经默认包含了 @ExtendWith(SpringExtension.class)。
|
||||
|
||||
因此,在 JUnit5 中只需要单独使用 @SpringBootTest 注解即可。其他需要自定义拓展的再用 @ExtendWith,不要再用 @RunWith 了。
|
||||
|
||||
|
||||
### mockito
|
||||
|
||||
Mockito 框架中最核心的两个概念就是 Mock 和 Stub。测试时不是真正的操作外部资源,而是通过自定义的代码进行模拟操作。我们可以对任何的依赖进行模拟,从而使测试的行为不需要任何准备工作或者不具备任何副作用。
|
||||
|
||||
1. 当我们在测试时,如果只关心某个操作是否执行过,而不关心这个操作的具体行为,这种技术称为 mock。比如我们测试的代码会执行发送邮件的操作,我们对这个操作进行 mock;测试的时候我们只关心是否调用了发送邮件的操作,而不关心邮件是否确实发送出去了。
|
||||
|
||||
2. 另一种情况,当我们关心操作的具体行为,或者操作的返回结果的时候,我们通过执行预设的操作来代替目标操作,或者返回预设的结果作为目标操作的返回结果。这种对操作的模拟行为称为 stub(打桩)。比如我们测试代码的异常处理机制是否正常,我们可以对某处代码进行 stub,让它抛出异常。再比如我们测试的代码需要向数据库插入一条数据,我们可以对插入数据的代码进行stub,让它始终返回1,表示数据插入成功。
|
||||
|
||||
### powermock
|
||||
|
||||
需要手动引入测试类。依赖mockito,注意版本的对应关系。
|
||||
|
||||
```xml
|
||||
<dependency>
|
||||
<groupId>org.powermock</groupId>
|
||||
<artifactId>powermock-api-mockito2</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.powermock</groupId>
|
||||
<artifactId>powermock-module-junit4</artifactId>
|
||||
</dependency>
|
||||
|
||||
```
|
||||
## 2 使用
|
||||
|
||||
### 注解
|
||||
|
||||
@RunWith:
|
||||
1. 表示运行方式,@RunWith(JUnit4TestRunner)、@RunWith(SpringRunner.class)、@RunWith(PowerMockRunner.class) 三种运行方式,分别在不同的场景中使用。
|
||||
2. 当一个类用@RunWith注释或继承一个用@RunWith注释的类时,JUnit将调用它所引用的类来运行该类中的测试而不是开发者去在junit内部去构建它。我们在开发过程中使用这个特性
|
||||
|
||||
@SpringBootTest:
|
||||
1. 注解制定了一个测试类运行了Spring Boot环境。提供了以下一些特性:
|
||||
1. 当没有特定的ContextConfiguration#loader()(@ContextConfiguration(loader=...))被定义那么就是SpringBootContextLoader作为默认的ContextLoader。
|
||||
2. 自动搜索到SpringBootConfiguration注解的文件。
|
||||
3. 允许自动注入Environment类读取配置文件。
|
||||
4. 提供一个webEnvironment环境,可以完整的允许一个web环境使用随机的端口或者自定义的端口。
|
||||
5. 注册了TestRestTemplate类可以去做接口调用。
|
||||
|
||||
2. 添加这个就能取到spring中的容器的实例,如果配置了@Autowired那么就自动将对象注入。
|
||||
|
||||
### 基本测试用例
|
||||
|
||||
Springboot整合JUnit的步骤
|
||||
1. 导入测试对应的starter
|
||||
|
||||
2. 测试类使用@SpringBootTest修饰
|
||||
|
||||
3.使用自动装配的形式添加要测试的对象。
|
||||
|
||||
```java
|
||||
@SpringBootTest(classes = {SpringbootJunitApplication.class})
|
||||
class SpringbootJunitApplicationTests {
|
||||
|
||||
@Autowired
|
||||
private UsersDao users;
|
||||
|
||||
@Test
|
||||
void contextLoads() {
|
||||
users.save();
|
||||
}
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
### mock单元测试
|
||||
因为单元测试不用启动 Spring 容器,则无需加 @SpringBootTest,因为要用到 Mockito,只需要自定义拓展 MockitoExtension.class 即可,依赖简单,运行速度更快。
|
||||
|
||||
可以明显看到,单元测试写的代码,怎么是被测试代码长度的好几倍?其实单元测试的代码长度比较固定,都是造数据和打桩,但如果针对越复杂逻辑的代码写单元测试,还是越划算的
|
||||
```java
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class HrServiceTest {
|
||||
@Mock
|
||||
private OrmDepartmentDao ormDepartmentDao;
|
||||
@Mock
|
||||
private OrmUserDao ormUserDao;
|
||||
@InjectMocks
|
||||
private HrService hrService;
|
||||
|
||||
@DisplayName("根据部门名称,查询用户")
|
||||
@Test
|
||||
void findUserByDeptName() {
|
||||
Long deptId = 100L;
|
||||
String deptName = "行政部";
|
||||
OrmDepartmentPO ormDepartmentPO = new OrmDepartmentPO();
|
||||
ormDepartmentPO.setId(deptId);
|
||||
ormDepartmentPO.setDepartmentName(deptName);
|
||||
OrmUserPO user1 = new OrmUserPO();
|
||||
user1.setId(1L);
|
||||
user1.setUsername("001");
|
||||
user1.setDepartmentId(deptId);
|
||||
OrmUserPO user2 = new OrmUserPO();
|
||||
user2.setId(2L);
|
||||
user2.setUsername("002");
|
||||
user2.setDepartmentId(deptId);
|
||||
List<OrmUserPO> userList = new ArrayList<>();
|
||||
userList.add(user1);
|
||||
userList.add(user2);
|
||||
|
||||
Mockito.when(ormDepartmentDao.findOneByDepartmentName(deptName))
|
||||
.thenReturn(
|
||||
Optional.ofNullable(ormDepartmentPO)
|
||||
.filter(dept -> deptName.equals(dept.getDepartmentName()))
|
||||
);
|
||||
Mockito.doReturn(
|
||||
userList.stream()
|
||||
.filter(user -> deptId.equals(user.getDepartmentId()))
|
||||
.collect(Collectors.toList())
|
||||
).when(ormUserDao).findByDepartmentId(deptId);
|
||||
|
||||
List<OrmUserPO> result1 = hrService.findUserByDeptName(deptName);
|
||||
List<OrmUserPO> result2 = hrService.findUserByDeptName(deptName + "error");
|
||||
|
||||
Assertions.assertEquals(userList, result1);
|
||||
Assertions.assertEquals(Collections.emptyList(), result2);
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
### 集成单元测试
|
||||
还是那个方法,如果使用Spring上下文,真实的调用方法依赖,可直接用下列方式
|
||||
```java
|
||||
@SpringBootTest
|
||||
class HrServiceTest {
|
||||
@Autowired
|
||||
private HrService hrService;
|
||||
|
||||
@DisplayName("根据部门名称,查询用户")
|
||||
@Test
|
||||
void findUserByDeptName() {
|
||||
List<OrmUserPO> userList = hrService.findUserByDeptName("行政部");
|
||||
Assertions.assertTrue(userList.size() > 0);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
还可以使用@MockBean、@SpyBean替换Spring上下文中的对应的Bean:
|
||||
```java
|
||||
@SpringBootTest
|
||||
class HrServiceTest {
|
||||
@Autowired
|
||||
private HrService hrService;
|
||||
@SpyBean
|
||||
private OrmDepartmentDao ormDepartmentDao;
|
||||
|
||||
@DisplayName("根据部门名称,查询用户")
|
||||
@Test
|
||||
void findUserByDeptName() {
|
||||
String deptName="行政部";
|
||||
OrmDepartmentPO ormDepartmentPO = new OrmDepartmentPO();
|
||||
ormDepartmentPO.setDepartmentName(deptName);
|
||||
Mockito.when(ormDepartmentDao.findOneByDepartmentName(ArgumentMatchers.anyString()))
|
||||
.thenReturn(Optional.of(ormDepartmentPO));
|
||||
List<OrmUserPO> userList = hrService.findUserByDeptName(deptName);
|
||||
Assertions.assertTrue(userList.size() > 0);
|
||||
}
|
||||
}
|
||||
```
|
||||
Reference in New Issue
Block a user