Spring整合Junit单元测试注意事项

本文介绍了如何整合Spring和Junit进行单元测试,强调在测试中对象的创建必须通过注解注入,不能使用new操作。同时提到了测试时遇到的问题及Spring降低耦合的原则。
摘要由CSDN通过智能技术生成
Spring整合Junit单元测试注意事项

​ Spring——牛逼框架,Junit——单元测试。用了Spring要做测试——Spring+Junit,开整。

  1. 导入spring整合junit的jar(坐标)

    <dependency>
         <groupId>junit</groupId>
         <artifactId>junit</artifactId>
         <version>4.12</version>
    </dependency>
    
  2. 使用Junit提供的一个注解把原有的main方法替换了,替换成spring提供的@Runwith

    @RunWith(SpringJUnit4ClassRunner.class)

  3. 告知spring的运行器,spring和ioc创建是基于xml还是注解的,并且说明位置@ContextConfiguration

    • locations:指定xml文件的位置,加上classpath关键字,表示在类路径下

      @ContextConfiguration(locations = "classpath:bean.xml")

    • classes:指定注解类所在地位置

      @ContextConfiguration(classes = SpringConfiguration.class)

    整完,开始测,走~

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations = "classpath:bean.xml")
    public class Test {
        private IAccountService accountService = new AccountServiceImpl();
        @Test
        public void test() {
            accountService.test();
        }
    }
    
    1. 创建对象
    2. 调用方法
    3. 来~跑起来,嘟驾~
      在这里插入图片描述
      😱为什么。。java.lang.NullPointerException。。。看下报错信息,嗯,看不懂,再瞅瞅,有认识的了,SpringJunit4ClassRunner,这不就是我整合时候修改的 main 方法嘛,Spring提供的。

    再想想Spring核心——IoC,AOP。还没有AOP的事儿啊,那就是容器了。难道我调用了Spring,就不能new对象了?再试试。。

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations = "classpath:bean.xml")
    public class Test {
        @Resource(name = "accountService")
        private IAccountService accountService;
    
        @Test
        public void test() {
            accountService.test();
        }
    }
    

    IAccountService我用注解注入总行了吧。走~然后。。真的就可以了🤔真的是。。

    至此,只能说,Spring牛逼,我用了你,我连想要有个增加耦合的机会都没有。

    总结:Spring整合了Junit做单元测试(其他时候还是可以new创建的,全都不让new也不现实),在对象创建时,只能使用注解注入,无法使用new创建。用BeanFactory工厂直接get也创建不了的呦~

    @Resource
    private BeanFactory beanFactory;
    IAccountService accountService = beanFactory.getAccountService();
    

    当然了,你都学了Spring了,还new啥new,new啥new,这不是违背Spring降低耦合的原则嘛,简直没事做(说给自己听的)

    ps:如果有小伙伴能够在test文件中new出来对象或者大佬觉得是错的,可以纠正我,万分感谢~我是小白一个,嗯。至此,溜啦

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值