Springboot UT 引入某些类
http://www.infoq.com/cn/articles/Unit-Testing-Complete-Integration-Testing-Begins
https://segmentfault.com/a/1190000010854538
前面一个部分讲解了如何使用Spring Testing工具来测试Spring项目,现在我们讲解如何使用Spring Boot Testing工具来测试Spring Boot项目。
在Spring Boot项目里既可以使用Spring Boot Testing工具,也可以使用Spring Testing工具。
在Spring项目里,一般使用Spring Testing工具,虽然理论上也可以使用Spring Boot Testing,不过因为Spring Boot Testing工具会引入Spring Boot的一些特性比如AutoConfiguration,这可能会给你的测试带来一些奇怪的问题,所以一般不推荐这样做。
例子1:直接加载Bean
使用Spring Boot Testing工具只需要将@ContextConfiguration改成@SpringBootTest即可,源代码见FooServiceImpltest:
@SpringBootTest(classes = FooServiceImpl.class)
public class FooServiceImplTest extends AbstractTestNGSpringContextTests {
@Autowired
private FooService foo;
@Test
public void testPlusCount() throws Exception {
assertEquals(foo.getCount(), 0);
foo.plusCount();
assertEquals(foo.getCount(), 1);
}
}
例子2:使用内嵌@Configuration加载Bean
源代码见FooServiceImpltest:
@SpringBootTest
public class FooServiceImplTest extends AbstractTestNGSpringContextTests {
@Autowired
private FooService foo;
@Test
public void testPlusCount() throws Exception {
assertEquals(foo.getCount(), 0);
foo.plusCount();
assertEquals(foo.getCount(), 1);
}
@Configuration
@Import(FooServiceImpl.class)
static class Config {
}
}
例子3:使用外部@Configuration加载Bean
@Configuration
@Import(FooServiceImpl.class)
public class Config {
}
@SpringBootTest(classes = Config.class)
public class FooServiceImplTest extends AbstractTestNGSpringContextTests {
@Autowired
private FooService foo;
@Test
public void testPlusCount() throws Exception {
assertEquals(foo.getCount(), 0);
foo.plusCount();
assertEquals(foo.getCount(), 1);
}
}
这个例子和例子2差不多,只不过将@Configuration放到了外部。
例子4:使用@SpringBootConfiguration
前面的例子@SpringBootTest的用法和@ContextConfiguration差不多。不过根据@SpringBootTest的文档:
它会尝试加载
@SpringBootTest(classes=...)的定义的Annotated classes。Annotated classes的定义在ContextConfiguration中有说明。如果没有设定
@SpringBootTest(classes=...),那么会去找当前测试类的nested @Configuration class如果上一步找到,则会尝试查找
@SpringBootConfiguration,查找的路径有:1)看当前测试类是否@SpringBootConfiguration,2)在当前测试类所在的package里找。
所以我们可以利用这个特性来进一步简化测试代码。
@SpringBootConfiguration
@Import(FooServiceImpl.class)
public class Config {
}
@SpringBootTest
public class FooServiceImplTest extends AbstractTestNGSpringContextTests {
@Autowired
private FooService foo;
@Test
public void testPlusCount() throws Exception {
assertEquals(foo.getCount(), 0);
foo.plusCount();
assertEquals(foo.getCount(), 1);
}
}
例子5:使用@ComponentScan扫描Bean
前面的例子我们都使用@Import来加载Bean,虽然这中方法很精确,但是在大型项目中很麻烦。
在常规的Spring Boot项目中,一般都是依靠自动扫描机制来加载Bean的,所以我们希望我们的测试代码也能够利用自动扫描机制来加载Bean。
@SpringBootConfiguration
@ComponentScan(basePackages = "me.chanjar.basic.service")
public class Config {
}
@SpringBootTest
public class FooServiceImplTest extends AbstractTestNGSpringContextTests {
@Autowired
private FooService foo;
@Test
public void testPlusCount() throws Exception {
assertEquals(foo.getCount(), 0);
foo.plusCount();
assertEquals(foo.getCount(), 1);
}
}
例子6:使用@SpringBootApplication
也可以在测试代码上使用@SpringBootApplication,它有这么几个好处:
自身
SpringBootConfiguration提供了
@ComponentScan配置,以及默认的excludeFilter,有了这些filter Spring在初始化ApplicationContext的时候会排除掉某些Bean和@Configuration启用了
EnableAutoConfiguration,这个特性能够利用Spring Boot来自动化配置所需要的外部资源,比如数据库、JMS什么的,这在集成测试的时候非常有用。
@SpringBootApplication(scanBasePackages = "me.chanjar.basic.service")
public class Config {
}
@SpringBootTest
public class FooServiceImplTest extends AbstractTestNGSpringContextTests {
@Autowired
private FooService foo;
@Test
public void testPlusCount() throws Exception {
assertEquals(foo.getCount(), 0);
foo.plusCount();
assertEquals(foo.getCount(), 1);
}
}
避免@SpringBootConfiguration冲突
当@SpringBootTest没有定义(classes=...,且没有找到nested @Configuration class的情况下,会尝试查询@SpringBootConfiguration,如果找到多个的话则会抛出异常:
Caused by: java.lang.IllegalStateException: Found multiple @SpringBootConfiguration annotated classes [Generic bean: class [...]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [/Users/qianjia/workspace-os/spring-test-examples/basic/target/test-classes/me/chanjar/basic/springboot/ex7/FooServiceImplTest1.class], Generic bean: class[me.chanjar.basic.springboot.ex7.FooServiceImplTest2]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [...]]
比如以下代码就会造成这个问题:
@SpringBootApplication(scanBasePackages = "me.chanjar.basic.service")
public class Config1 {
}
@SpringBootApplication(scanBasePackages = "me.chanjar.basic.service")
public class Config2 {
}
@SpringBootTest
public class FooServiceImplTest extends AbstractTestNGSpringContextTests {
// ...
}
解决这个问题的方法有就是避免自动查询@SpringBootConfiguration:
定义
@SpringBootTest(classes=...)提供nested @Configuration class
最佳实践
除了单元测试(不需要初始化ApplicationContext的测试)外,尽量将测试配置和生产配置保持一致。比如如果生产配置里启用了AutoConfiguration,那么测试配置也应该启用。因为只有这样才能够在测试环境下发现生产环境的问题,也避免出现一些因为配置不同导致的奇怪问题。
在测试代码之间尽量做到配置共用,这么做的优点有3个:
能够有效利用Spring TestContext Framework的缓存机制,ApplicationContext只会创建一次,后面的测试会直接用已创建的那个,加快测试代码运行速度。
当项目中的Bean很多的时候,这么做能够降低测试代码复杂度,想想如果每个测试代码都有一套自己的@Configuration或其变体,那得多吓人。
参考文档
例子7:
使用
@ContextHierarchy({
@ContextConfiguration(classes = {ServiceTestConfig.class}, loader = AnnotationConfigContextLoader.class)
})
@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration( loader=AnnotationConfigContextLoader.class, classes=ApplicationContextTestResourceNameType.class)public class FieldResourceInjectionTest { @Resource(name="namedFile") private File defaultFile; @Test public void givenResourceAnnotation_WhenOnField_ThenDependencyValid(){ assertNotNull(defaultFile); assertEquals("namedFile.txt", defaultFile.getName()); }}@Configurationpublic class ApplicationContextTestResourceNameType { @Bean(name="namedFile") public File namedFile() { File namedFile = new File("namedFile.txt"); return namedFile; }}Springboot UT 引入某些类的更多相关文章
- Thinkphp 零散知识点(caa/js路径,引入第三方类,ajax返回,session/cookie)
一.关于JS和CSS路径问题 1.找路径是从入口文件index.php来找的,而不是从文件本身所在位置来找, 因为我们访问时是访问的入口文件 2.在存放JS和CSS的时候可以放到public文件夹下 ...
- 尚硅谷springboot学习5-主入口类说明
package com.atguigu; import org.springframework.boot.SpringApplication; import org.springframework.b ...
- SpringBoot启动加载类ApplicationRunner
SpringBoot启动加载类ApplicationRunner 有时希望项目在启动的时候加载一些系统参数,就要用到ApplicationRunner ApplicationRunner是一个接口,我 ...
- springboot服务引入外部jar包在windows运行正常,在linux环境上无法加载到引入jar包的类
一.问题描述 最近开发了一个springboot程序,需要依赖第三方jar包,这个jar包无法直接通过pom远程仓库下载,需要从自己本地引入,于是配置pom文件如下:将本地jar包引入工程,syste ...
- springboot中引入zookeeper,生成 配置类
1.application.properties zookeeper.address=@mvn.zookeeper.address@ zookeeper.namespace=@mvn.zookeepe ...
- SSM项目 以及 springboot 中引入swagger2的方法
swagger2是一个非常好用的接口文档,在开发的过程中方便前后端接口的交接. 下面我们就来讲讲在使用java时,分别在SSM框架,以及springboot+mybatis框架中引入swagger2的 ...
- SpringBoot入门02-配置类
引入 Spring Boot的底层已经有了Spring MVC Spring Boot习惯优先的思想,很多配置都是可省的 不需要配置web.xml文件 不需要服务层的xml配置 不需要dao层的xml ...
- SpringBoot内置工具类,告别瞎写工具类了
不知大家有没有注意到,接手的项目中存在多个重复的工具类,发现其中很多功能,Spring 自带的都有.于是整理了本文,希望能够帮助到大家! 一.断言 断言是一个逻辑判断,用于检查不应该发生的情况 Ass ...
- 引入DecimalFormat类进行数字格式化操作
引入语句:import java.text.DecimalFormat; 首先创建DecimalFormat类对象,利用类对象调用Format()方法进行格式化操作.这里有两种方法:①.Decimal ...
随机推荐
- java基础学习总结——static关键字
一.static关键字
- Remon Spekreijse CSerialPort串口类的修正版2014-01-10
转自:http://m.blog.csdn.net/blog/itas109/18358297# 2014-1-16阅读691 评论0 如需转载请标明出处:http://blog.csdn.net/i ...
- 我的NHibernate曲折之行
之前,看过很多NHibernate的东西.特别是 YJingLee的NHibernate之旅系列比较经典.看得多了,但是还没有真正的从头到尾的做过一边.今天从头到尾做了一遍,发现问题还真多.我就将我做 ...
- Linux内核相关常见面试题
转:http://www.embeddedlinux.org.cn/html/xinshourumen/201303/11-2475.html 本文详细阐述了linux内核相关的开发职位面试中 ...
- spring整合mybatis步骤分析
1.spring配置datasource bean的时候,不同的数据库连接方式有有不同的datasource实现类. 比如采用c3p0数据库连接池,要用c3p0的datasource实现类 com.m ...
- Redis持久化RDB和AOF优缺点是什么,怎么实现的?我应该用哪一个?
原文http://www.ymq.io/2018/03/24/redis/ Redis是一种高级key-value数据库.数据可以持久化,而且支持的数据类型很丰富.有字符串,链表,集 合和有序集合.支 ...
- memcached-session-manager配置
原文地址: http://chenzhou123520.iteye.com/blog/1650212 声明:本篇文章是根据memcached-session-manager官方配置方法wiki页面翻译 ...
- 【docker】docker部署spring boot项目在服务器上
IDE:idea 工具:docker spring boot:2.0.1 ======================================== 简单记录一下流程,以供参考: 第一步:首先得 ...
- tomcat配置管理员帐号密码
进入tomcat目录下的conf中的tomcat-users.xml: 增加以下语句 <role rolename="admin-gui"/><role role ...
- P值(P-value),“差异具有显著性”和“具有显著差异”
郑冰刚提到P值,说P值的定义(着重号是笔者加的,英文是从WikiPedia摘来的): P值就是当原假设为真时,比所得到的样本观察结果更极端的结果出现的概率. The P-value is the pr ...