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());

    }



}

相关推荐

  1. Spring注解配置

    2024-05-25 20:29:01       46 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-05-25 20:29:01       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-05-25 20:29:01       106 阅读
  3. 在Django里面运行非项目文件

    2024-05-25 20:29:01       87 阅读
  4. Python语言-面向对象

    2024-05-25 20:29:01       96 阅读

热门阅读

  1. DQL( 数据查询语言)

    2024-05-25 20:29:01       32 阅读
  2. 客户机/服务器交互模式

    2024-05-25 20:29:01       34 阅读
  3. 程序员搞副业的障碍有那些?

    2024-05-25 20:29:01       31 阅读
  4. em,rem,vw,vh,px,rpx,%的用法

    2024-05-25 20:29:01       34 阅读
  5. Spring Boot: 为 JPA 插上翅膀的 QueryDSL

    2024-05-25 20:29:01       31 阅读
  6. leetcode143-Reorder List

    2024-05-25 20:29:01       29 阅读
  7. 实现C++ List,双端链表和静态链表

    2024-05-25 20:29:01       30 阅读