Spring整合JUnit
Spring整合JUnit
1、导入依赖
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope></dependency><dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>5.3.16</version></dependency>
- junit 是使用 @Test 注解时需要使用到的 jar 包。
- spring-test 是 Spring 框架提供的测试包。
2、编写测试类
@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(classes = SpringConfig.class)public class UserServiceTest { @Autowired private UserService userService; @Test public void testSelectById(){ System.out.println(userService.selectById(3)); }}
- 需要在测试类上加上两个注解。
- @RunWith 注解用于设置测试类运行器,一般我们都会将其设置为 “SpringJUnit4ClassRunner.class”。
- @ContextConfiguration 注解用于设置 Spring 的核心配置类,使用 classes 属性完成,如果有多个,可以使用数组{}形式指定。
- 整合后的测试类支持自动装配注入 bean ,当我们测试 bean 时,无需再通过获取 ApplicationContext 方式实现,直接将所测试的 bean 声明为属性,然后使用 @Autowired 注解自动装配即可。
- 测试方法上标注 @Test ,之后在方法体中测试即可。
3、测试结果