欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spring boot 参考手册——第40章测试阅读笔记和注意点

程序员文章站 2022-06-08 22:07:02
...
Spring boot 参考手册——第40章测试功能 阅读笔记和注意点

基于Spring boot 1.3.8.RELEASE版本

40.3 测试Spring Boot应用

1.spring-boot-test在创建Spring boot测试所需要的ApplicationContext时和创建Spring Framework的测试所需要的ApplicationContext并无太大区别,但有一点要注意:

像外置属性、日志记录及其他Spring boot特性需要基于SpringApplication创建

2.spring-boot-test 提供的注解@SpringApplicationConfiguration 可以替换spring-test的注解 @ContextConfiguration,如果要使用@SpringApplicationConfiguration注解配置ApplicationContext那么必须通过SpringApplication创建。

3.spring-boot-test通过查找注解@WebIntegrationTest 或 @WebAppConfiguration来猜测测试的是否是WEB应用。但注解 @WebAppConfiguration是spring-test框架提供的。

4.通过添加环境属性到@WebIntegrationTest注解可以定制
如指定Web集成测试的使用端口
@WebIntegrationTest("server.port:9000")

如果想使用随机端口可以这样做:
@WebIntegrationTest({"server.port=0", "management.port=0"})


40.4 spring-boot-test 提供的实用工具类说明

1.如果在测试中不需要@SpringApplicationConfiguration注解提供的全部特性可使用
  ConfigFileApplicationContextInitializer
 
@ContextConfiguration(classes = Config.class,
    initializers = ConfigFileApplicationContextInitializer.class)

2.EnvironmentTestUtils类允许你快速向ConfigurableEnvironment或ConfigurableApplicationContext对象添加环境属性
EnvironmentTestUtils.addEnvironment(env, "org=Spring", "name=Boot");


3.使用OutputCapture类可以捕捉System.out 和 System.err 的输出。

4.TestRestTemplate类提供便捷的方式使得在任何一种情况下,以一种测试友好的方式运行:不遵循重定向(这样可以断言响应位置)、忽略cookie(无状态的)以及不在服务器端错误上引发异常