Spring整合单元测试
目的
减少再我们测试的时候不停的实例化或者不同的构建Spring容器 就能省略以下代码
//加载XML文件,构建Spring容器的代码
new AnnotationConfigApplicationContext("对应配置类的字节码对象");
new ClassPathXmlApplicationContext("applicationContext.xml");
开发步骤
1.首先需要再pom.xml文件中添加坐标依赖
<!--引入spring-test坐标依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.5.RELEASE</version>
<scope>test</scope>
</dependency>
<!--引入Junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.1</version>
<scope>test</scope>
</dependency>
2.在测试类上面添加注解, @RunWith(SpringJUnit4ClassRunner.class) 目的就是帮助我我们创建Spring容器
3.在测试类上卖弄添加注解 @ContextConfiguration(“classpath:applicationContext.xml”) 把主配置文件的类路径放进来,
到这一步空间一级建立完毕
在测试包内部
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class SpringTest {
4.从容器中取出我们u需要的bean元素。
- getBean()
- 采用注解的属性注入。@AutoWired @Resource 给类进行属性注入
首先如果这里需要使用,那么前面就必须要有对应属性被放入内存空间,否则无法获得
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class SpringTest {
// 属性注入
@Resource(name = "c1") //因为内存里面创建了多个对象所以要采用这种方式指定
private Car car;
@Autowired //因为内存里面只有一个他的对象所以考研直接使用
private UserController userController;
// 注入UserService类对象
@Autowired //因为内存里面只有一个他的对象所以考研直接使用
private UserService userService;
// 注入Proxy01类对象
@Autowired //因为内存里面只有一个他的对象所以考研直接使用
private Proxy01 proxy01;
// 注入Proxy02类对象
@Autowired //因为内存里面只有一个他的对象所以考研直接使用
private Proxy02 proxy02;