Spring整合单元测试

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;
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值