Spring 提供了专门的模块用来对 Spring 进行测试:
相关注解说明
1、@RunWith():
- 用于指定 junit 运行环境,是 junit 提供给其他框架测试环境接口扩展
- 为了便于使用spring的依赖注入,spring提供了 org.springframework.test.context.junit4.SpringJUnit4ClassRunner 作为 Junit 测试环境,例如:@RunWith( SpringJUnit4ClassRunner.class )
2、@ContextConfiguration:Spring 提供的注解,用于导入 Spring 的配置文件
- classes={ Config.class, … }:用来加载 Spring 配置类
- locations = { “classpath:springContext.xml” , … }:用来加载 Spring 配置文件
3、@WebAppConfiguration:注解在测试类上,用来指定声明加载 ApplicationContext 是一个 WebApplicationContext,它的属性指定的是 web 资源的位置,默认为 src/main/webapp
4、@Before:在测试前进行的初始化工作
5、@After:在测试后进行的清理工作
依赖引入
引入 junit 和 spring-test 依赖:
<dependencies><!-- springMVC环境 --><dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>5.3.1</version></dependency><!-- 测试依赖 --><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.13.1</version><scope>test</scope></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>5.3.1</version></dependency></dependencies>
Spring 项目测试
1、创建配置类 DemoConfig
@Configurationpublic class DemoConfig {}
2、创建测试类
@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(classes = {DemoConfig.class})public class DemoConfigTest {@AutowiredApplicationContext context;@Testpublic void name() {System.out.println(context);}}
