Spring框架整合junit:包含配置文件的方式以及纯注解开发的方式

Spring框架整合junit:包含配置文件的方式以及纯注解开发的方式

Spring框架合集:
Spring框架核心IOC的使用:IOC的作用+Bean管理+实例化Bean的方式+DI依赖注入
Spring框架核心IOC的使用:配置式开发+注解式开发+纯注解式开发

1. 准备工作

添加pom依赖

        <!-- spring整合junit -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.0.2.RELEASE</version>
            <scope>test</scope>
        </dependency>

2. 配置文件的方式

如果不整合junit,那每次在测试类中都要加载配置文件,每次都要 new 一个 ClassPathXmlApplicationContext ,整合之后可以直接调用需要测试类的方法

2.1 未整合前

public class UserServiceTest {


    //spring ioc 的方式创建对象,ioc是一个map,key-value形式,key是对象的标识,value是ioc创建的对象
    @Test
    public void run1(){
        //创建spring ioc工厂,主要是为了加载spring的配置文件
    ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        //获取bean对象

	UserService userService = (UserService) ac.getBean("xx");  //强制类型转换
    userService.hello();


    }

}

2.2 整合以后

这里的@ContextConfiguration(“classpath:applicationContext.xml”)里面的applicationContext.xml是配置文件,@Autowired是为userService注入值

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class UserServiceTest {
    @Autowired
    private UserService userService;

    @Test
    public void run1(){

        userService.hello();


    }

}

3. 纯注解开发的方式

3.1 未整合前

未整合前每次需要new一个AnnotationConfigApplicationContext,创建工厂加载配置类,整合以后可以直接调用需要测试的类的方法
整合前的写法


public class UserServiceTest {
    @Autowired
    private AccountService accountService;
    @Test
    public void run(){


    //创建工厂,加载配置类
    ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfig.class);
    AccountService accountService = (AccountService) ac.getBean("accountServiceImpl");
    System.out.println(accountService.findAll());

    }



}

3.2 整合后

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfig.class)
public class UserServiceTest {
    @Autowired
    private AccountService accountService;
    @Test
    public void run(){

    System.out.println(accountService.findAll());

    }



}
  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值