SpringBoot 单元测试及常用配置
1 SpringBoot 单元测试
作为一名后端程序员需要会单元测试。
主要是通过 @RunWith 和 @SpringBootTest 注解来开启单元测试功能
package com.pky.hello.springboot.controller;
import com.pky.hello.springboot.HelloSpringbootApplication;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = HelloSpringbootApplication.class)
public class LoginControllerTest {
@Autowired
LoginController loginController;
@Test
public void loginTest() {
System.out.println(loginController.login());
}
}
点击运行 loginTest(),测试成功后控制台会打印“登录成功”。
2 常用配置
Spring Boot 中的一些常用配置,比如:自定义 Banner、配置日志、关闭特定的自动配置等。
2.1 自定义 Banner
在 Spring Boot 启动的时候会有一个默认的启动图案如图 2.1 所示:
图 2.1
此时我们想更改启动图案,如下操作:
- 我们在 src/main/resources 目录下新建一个 banner.txt
- 通过 http://patorjk.com/software/taag 网站生成字符串,将网站生成的字符复制到 banner.txt 中
再次运行这个程序
${AnsiColor.BRIGHT_RED}
////////////////////////////////////////////////////////////////////
// _ooOoo_ //
// o8888888o //
// 88" . "88 //
// (| ^_^ |) //
// O\ = /O //
// ____/`---'\____ //
// .' \\| |// `. //
// / \\||| : |||// \ //
// / _||||| -:- |||||- \ //
// | | \\\ - /// | | //
// | \_| ''\---/'' | | //
// \ .-\__ `-` ___/-. / //
// ___`. .' /--.--\ `. . ___ //
// ."" '< `.___\_<|>_/___.' >'"". //
// | | : `- \`.;`\ _ /`;.`/ - ` : | | //
// \ \ `-. \_ __\ /__ _/ .-` / / //
// ========`-.____`-.___\_____/___.-`____.-'======== //
// `=---=' //
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ //
// 佛祖保佑 永不宕机 永无BUG //
////////////////////////////////////////////////////////////////////
常用属性设置:
- ${AnsiColor.BRIGHT_RED}:设置控制台中输出内容的颜色。
- ${application.version}:用来获取 MANIFEST.MF 文件中的版本号。
- ${application.formatted-version}:格式化后的。
- ${application.version}: 版本信息。
- ${spring-boot.version}:Spring Boot 的版本号。
- ${spring-boot.formatted-version}:格式化后的 。
- ${spring-boot.version}: 版本信息。
2.2 配置文件
Spring Boot 项目使用一个全局的配置文件 application.properties 或者是 application.yml,一般我们放到 resources 下。
- application.properties 中修改端口号及默认访问路径
server.port=9090
server.context-path=/v1/hello_springboot
- 或在 application.yml 中修改
server:
port: 9090
servlet:
context-path: /v1/hello_springboot
- 效果如图 2.1 所示
图 2.1
2.3 日志配置
Spring Boot 对各种日志框架都做了支持,我们可以通过配置来修改默认的日志的配置
默认情况下,Spring Boot 使用 Logback 作为日志框架
- 在 application.yml 中添加日志配置
server:
port: 9090
# 默认路径
servlet:
context-path: /v1/hello_springboot
logging:
# 文件名
file: hello-springboot.log
# 日志级别
level:
com:
pky: DEBUG
- 运行项目后,浏览器输入 url 后,会在项目根目录下出现一个 hello.springboot.log 日志文件,里面是项目运行的日志。