目錄
1,springboot使用單元測試
A:springboot使用單元測試需要引入一個單元測試啓動器,該啓動器的座標爲:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
B:編寫單元測試類
和springboot啓動器一樣需要編寫主程序類,單元測試啓動器也需要寫對應的一個單元測試類,需要兩個註解:
@RunWith(SpringRunner.class)
@SpringBootTest(classes={App.class})
第一個註解表示的是單元測試的啓動方式;第二個標註的是這個類屬於一個單元測試類,第二需要的參數爲啓動類的class文件對象。
在方法上需要加入@Test註解,表示該方法爲單元測試方法。
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes={App.class})
public class TestJunit {
@Resource
private Person person;
@Test
public void show(){
System.out.print(person);
}}
測試:
2,使用日誌框架
springboot的日誌框架是用 SLF4j和logback;本次使用的是log4j2, 就算使用別的日誌框架,springboot在整合的時候也會將其他日誌框架的底層依賴換成SLF4j和logback。
springboot的記錄方式有如下五種
- trace:打印字面,
- debug:打印bug調試
- info:打印編譯信息(默認)
- warn:打印警告信息
- error:打印錯誤信息
A:導入日誌啓動器
需要在web啓動器中添加:
<exclusions>
<exclusion>
<artifactId>spring-boot-starter-logging</artifactId>
<groupId>org.springframework.boot</groupId>
</exclusion>
</exclusions>
之後導入日誌啓動器:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
B:編寫日誌
springboot默認將日誌打印到控制檯,我們可以通過在全局配置文件中設置日誌的默認值
#啓動日誌記錄
logging.level.com.atguigu=trace
#將日誌打印到指定文件,沒有該文件,就不記錄
logging.path=log.log
#將日誌打印到指定文件,沒有該文件,就創建這個文件
logging.file=springboot.log
# 在控制檯輸出的日誌的格式
logging.pattern.console=%d{yyyy-MM-dd} [%thread] %-5level %logger{50} - %msg%n
# 指定文件中日誌輸出的格式
logging.pattern.file=%d{yyyy-MM-dd} === [%thread] === %-5level === %logger{50} ==== %msg%n
運行項目就可以查看日誌文件了。