Spring / Spring Boot Testing | 笔记
记录Spring Boot 开发中的测试手段。
😍 添加 spring-boot-starter-test 依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency>
spring-boot-starter-test 提供的依赖有 spring-boot-starter-logging, spring-boot, junit, mockito-core, hamcrest-library, spring-test。
-
JPA 测试
@RunWith(SpringRunner.class)
@DataJpaTest
@AutoConfigureTestDatabase(replace = Replace.NONE)
public class JPATest {
Logger logger = LoggerFactory.getLogger(JPATest.class);
@Autowired
private StudentHealthLogRepository logRep;
@Test
public void testJPA() {
System.out.println("Hello Spring Data JPA Test");
Date date = Date.valueOf("2020-03-24");
Integer total = logRep.countChickInStudent(date);
logger.info("{} chick int count is {}", date, total);
}
}
这个用来测试 Repository 层的 StudentHealthLogRepository 接口(自动装配),logger 代替 println() 方法打印输出内容,这个小测试是用来测试 logRep 的 countChickInStudent() 方法是否能正常返回结果。你可以自由更换测试任意的 repository 接口和 方法。
@RunWith(SpringRunner.class) 提供了spring boot 测试功能和 junit 之间的连接,如果你想在 junit 中使用任何 spring boot 测试功能,这个注解是必备的。
@DataJpaTest 提供了测试持久层必备的启动内容。
-
配置 H2,一个内存数据库 配置 Hibernate 、Spring Data 和 DataSource 执行一个 @EntiryScan 打开 SQL Logging
@AutoConfigureTestDatabase(replace = Replace.NONE) 用来配置一个测试用的数据库来代替应用中定义的数据库或DataSource,这里不想让测试数据库来代替应用中定义的数据库,因此把该注解的 replace 属性 设置位 None,其中 Replace 是 AutoConfigureTestDatabase注解中的内部 枚举类,取值有 ANY、AUTO_CONFIGURED 和 None。源码如下👇
/**
* Annotation that can be applied to a test class to configure a test database to use
* instead of any application defined or auto-configured {@link DataSource}.
*
* @author Phillip Webb
* @since 1.5.0
* @see TestDatabaseAutoConfiguration
*/
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@ImportAutoConfiguration
@PropertyMapping("spring.test.database")
public @interface AutoConfigureTestDatabase {
/**
* Determines what type of existing DataSource beans can be replaced.
* @return the type of existing DataSource to replace
*/
@PropertyMapping(skip = SkipPropertyMapping.ON_DEFAULT_VALUE)
Replace replace() default Replace.ANY;
/**
* The type of connection to be established when {@link #replace() replacing} the data
* source. By default will attempt to detect the connection based on the classpath.
* @return the type of connection to use
*/
EmbeddedDatabaseConnection connection() default EmbeddedDatabaseConnection.NONE;
/**
* What the test database can replace.
*/
enum Replace {
/**
* Replace any DataSource bean (auto-configured or manually defined).
*/
ANY,
/**
* Only replace auto-configured DataSource.
*/
AUTO_CONFIGURED,
/**
* Dont replace the application default DataSource.
*/
NONE
}
}
-
WebMvc测试 智能的 Spring Boot 测试 WebFlux 测试 Jdbc 测试 Jooq 测试 DataMongo 测试 DataRedis 测试 DataLdap 测试 RestClient 测试
挖个坑,以后填 😂
