SpringBootTest注解

@SpringBootTest注解 --基于SpringBoot2.5.7版本

SpringBootTest介绍

可以在运行基于Spring Boot的测试的测试类上指定的注释。在常规的Spring TestContext框架之上提供了以下特性:

  • 默认提供SpringBootContextLoader作为ContextLoader,也通过 @ContextConfiguration(loader=…)来自定义

  • 若没有显示指定,将查找嵌套的@Configuration类,然后返回到SpringBootConfiguration搜索配置Spring boot 官方说明

  • 允许使用properties属性定义自定义环境属性。

  • 允许使用args属性定义应用程序参数。

  • 支持不同webEnvironment模式,包括自定义运行web服务器监听或默认为随机端口

  • web服务模式下,自动注册一个TestRestTemplate和/或WebTestClient bean用于web测试

配置名称备注
value配置属性
properties配置属性
args应用启动参数
classes指定加载容器上下文配置类,等同于@ContextConfiguration中的class,若没有显示指定,将查找嵌套的@Configuration类,然后返回到SpringBootConfiguration搜索配置

关于 aliasFor可以参考 spring 官方

SpringBootTest源码

@Target(ElementType.TYPE)//注解只能用于Class, interface (including annotation type), or enum declaration
@Retention(RetentionPolicy.RUNTIME)//注释将由编译器记录在类文件中,并在运行时由VM保留,因此可以反射性地读取它们。
@Documented
@Inherited //允许子类继承
@BootstrapWith(SpringBootTestContextBootstrapper.class)
@ExtendWith(SpringExtension.class)
public @interface SpringBootTest {

	/**
	 * Alias for {@link #properties()}.
	 * @return the properties to apply
	 */
	@AliasFor("properties")
	String[] value() default {};

	/**
	 * Properties in form {@literal key=value} that should be added to the Spring
	 * {@link Environment} before the test runs.
	 * @return the properties to add
	 */
	@AliasFor("value")
	String[] properties() default {};

	/**
	 * Application arguments that should be passed to the application under test.
	 * @return the application arguments to pass to the application under test.
	 * @see ApplicationArguments
	 * @see SpringApplication#run(String...)
	 * @since 2.2.0
	 */
	String[] args() default {};

	/**
	 * The <em>component classes</em> to use for loading an
	 * {@link org.springframework.context.ApplicationContext ApplicationContext}. Can also
	 * be specified using
	 * {@link ContextConfiguration#classes() @ContextConfiguration(classes=...)}. If no
	 * explicit classes are defined the test will look for nested
	 * {@link Configuration @Configuration} classes, before falling back to a
	 * {@link SpringBootConfiguration @SpringBootConfiguration} search.
	 * @see ContextConfiguration#classes()
	 * @return the component classes used to load the application context
	 */
	Class<?>[] classes() default {};

	/**
	 * The type of web environment to create when applicable. Defaults to
	 * {@link WebEnvironment#MOCK}.
	 * @return the type of web environment
	 */
	WebEnvironment webEnvironment() default WebEnvironment.MOCK;

	/**
	 * An enumeration web environment modes.
	 */
	enum WebEnvironment {

		/**
		 * Creates a {@link WebApplicationContext} with a mock servlet environment if
		 * servlet APIs are on the classpath, a {@link ReactiveWebApplicationContext} if
		 * Spring WebFlux is on the classpath or a regular {@link ApplicationContext}
		 * otherwise.
		 */
		MOCK(false),

		/**
		 * Creates a web application context (reactive or servlet based) and sets a
		 * {@code server.port=0} {@link Environment} property (which usually triggers
		 * listening on a random port). Often used in conjunction with a
		 * {@link LocalServerPort @LocalServerPort} injected field on the test.
		 */
		RANDOM_PORT(true),

		/**
		 * Creates a (reactive) web application context without defining any
		 * {@code server.port=0} {@link Environment} property.
		 */
		DEFINED_PORT(true),

		/**
		 * Creates an {@link ApplicationContext} and sets
		 * {@link SpringApplication#setWebApplicationType(WebApplicationType)} to
		 * {@link WebApplicationType#NONE}.
		 */
		NONE(false);

		private final boolean embedded;

		WebEnvironment(boolean embedded) {
			this.embedded = embedded;
		}

		/**
		 * Return if the environment uses an {@link ServletWebServerApplicationContext}.
		 * @return if an {@link ServletWebServerApplicationContext} is used.
		 */
		public boolean isEmbedded() {
			return this.embedded;
		}

	}

}

demo案例

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT,
        properties = "server.port=8081", args = "--spring.application.name=demoTest",
        classes = AppApplication.class)
@Import(MyConfig.class)
public class SpringBootDemoTest {
    @Autowired
    private ApplicationContext applicationContext;
    @Value("${spring.application.name}")
    private String appName;

    @Autowired(required = false)
    private MyConfig myConfig;

    @Test
    void AppApplicationTest() {
        assert ("demoTest".equals(appName));
        assertThat(myConfig).isNotNull().extracting("cfgName").isEqualTo("11");
        assertThat(applicationContext).isNotNull();
    }
}
import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class MyConfig {
    private String cfgName = "11";
}

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

/**
 * @author bearboy80
 */
@SpringBootApplication
public class AppApplication {
    public static void main(String[] args) {
        SpringApplication.run(AppApplication.class, args);
    }
}

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
1. 环境搭建 首先下载安装好MySQL和IDEA,创建一个SpringBoot项目,在pom.xml文件中引入相关依赖: ``` <dependencies> <!-- Spring Boot --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- Mybatis-Plus --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.1</version> </dependency> <!-- MySQL 驱动 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <!-- layui --> <dependency> <groupId>com.layui</groupId> <artifactId>layui</artifactId> <version>2.5.7</version> </dependency> </dependencies> ``` 同时,在application.properties文件中配置数据库相关信息: ``` # MySQL spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/employee_management?serverTimezone=Asia/Shanghai&useSSL=false&allowPublicKeyRetrieval=true spring.datasource.username=root spring.datasource.password=123456 # Mybatis-Plus mybatis-plus.config.location=classpath:mybatis/mybatis-plus-config.xml ``` 2. 创建Mybatis-Plus映射文件 在resources目录下创建mybatis文件夹并添加mybatis-plus-config.xml文件,在其中添加@EnableTransactionManagement注解,开启事务管理。 在mybatis文件夹下创建mapper文件夹,并创建EmployeeMapper.java和LogMapper.java文件,定义员工和日志的SQL操作: EmployeeMapper.java: ```java public interface EmployeeMapper extends BaseMapper<Employee> { List<Employee> getEmployeeList(); Integer deleteEmployee(Integer id); } ``` LogMapper.java: ```java public interface LogMapper extends BaseMapper<Log> { List<Log> getLogList(); } ``` 3. 创建Java代码 在src/main/java下创建entity、service和controller包,并分别创建Employee、Log、EmployeeService、LogService、EmployeeController和LogController。 Employee.java: ```java @Data public class Employee { @TableId(type = IdType.AUTO) private Integer id; private String name; private Integer age; private String gender; private String address; private String phone; @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") private Date createTime; } ``` Log.java: ```java @Data public class Log { @TableId(type = IdType.AUTO) private Integer id; private Integer userId; private String operation; private String method; private String params; private String ip; private Date createTime; } ``` EmployeeService.java: ```java public interface EmployeeService extends IService<Employee> { List<Employee> getEmployeeList(); Integer deleteEmployee(Integer id); } ``` EmployeeServiceImpl.java: ```java @Service public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements EmployeeService { @Autowired private EmployeeMapper employeeMapper; @Override public List<Employee> getEmployeeList() { return employeeMapper.getEmployeeList(); } @Override public Integer deleteEmployee(Integer id) { return employeeMapper.deleteEmployee(id); } } ``` LogService.java: ```java public interface LogService extends IService<Log> { List<Log> getLogList(); } ``` LogServiceImpl.java: ```java @Service public class LogServiceImpl extends ServiceImpl<LogMapper, Log> implements LogService { @Autowired private LogMapper logMapper; @Override public List<Log> getLogList() { return logMapper.getLogList(); } } ``` EmployeeController.java: ```java @RestController @RequestMapping("/employee") public class EmployeeController { @Autowired private EmployeeService employeeService; @GetMapping("/list") public List<Employee> getEmployeeList() { return employeeService.getEmployeeList(); } @DeleteMapping("/delete") public Integer deleteEmployee(Integer id) { return employeeService.deleteEmployee(id); } } ``` LogController.java: ```java @RestController @RequestMapping("/log") public class LogController { @Autowired private LogService logService; @GetMapping("/list") public List<Log> getLogList() { return logService.getLogList(); } } ``` 4. 创建HTML页面 在src/main/resources/static下创建employee和log文件夹,并分别创建index.html和log.html文件: index.html: ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>员工管理</title> <link rel="stylesheet" href="/layui/css/layui.css"> <script src="/layui/layui.js"></script> </head> <body> <table class="layui-table"> <thead> <tr> <th>ID</th> <th>姓名</th> <th>年龄</th> <th>性别</th> <th>地址</th> <th>电话</th> <th>创建时间</th> <th>操作</th> </tr> </thead> <tbody id="employee_list"></tbody> </table> <script> $(document).ready(function () { layui.use(['layer', 'table'], function () { var $ = layui.jquery; var layer = layui.layer; var table = layui.table; // 初始化表格 table.render({ elem: '#employee_list' ,url: '/employee/list' ,cols: [[ {field: 'id', title: 'ID', sort: true} ,{field: 'name', title: '姓名'} ,{field: 'age', title: '年龄'} ,{field: 'gender', title: '性别'} ,{field: 'address', title: '地址'} ,{field: 'phone', title: '电话'} ,{field: 'createTime', title: '创建时间', sort: true} ,{fixed: 'right', title: '操作', toolbar: '#barDemo', width: 150} ]] ,page: true }); // 监听工具条 table.on('tool(test)', function(obj){ var data = obj.data; if(obj.event === 'del'){ layer.confirm('确认删除', function(index){ $.ajax({ type: 'DELETE', url: '/employee/delete', data: {id: data.id}, success: function () { obj.del(); layer.close(index); } }); }); } }); }); }); </script> <script type="text/html" id="barDemo"> <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a> </script> </body> </html> ``` log.html: ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>日志管理</title> <link rel="stylesheet" href="/layui/css/layui.css"> <script src="/layui/layui.js"></script> </head> <body> <table class="layui-table"> <thead> <tr> <th>ID</th> <th>用户ID</th> <th>操作</th> <th>方法</th> <th>参数</th> <th>IP地址</th> <th>时间</th> </tr> </thead> <tbody id="log_list"></tbody> </table> <script> $(document).ready(function () { layui.use(['layer', 'table'], function () { var $ = layui.jquery; var layer = layui.layer; var table = layui.table; // 初始化表格 table.render({ elem: '#log_list' ,url: '/log/list' ,cols: [[ {field: 'id', title: 'ID', sort: true} ,{field: 'userId', title: '用户ID', sort: true} ,{field: 'operation', title: '操作'} ,{field: 'method', title: '方法'} ,{field: 'params', title: '参数'} ,{field: 'ip', title: 'IP地址'} ,{field: 'createTime', title: '时间', sort: true} ]] ,page: true }); }); }); </script> </body> </html> ``` 5. 运行程序 在MySQL中创建employee_management数据库,并在其中创建employee和log表,运行程序即可在浏览器中访问相关页面实现员工和日志的管理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值