zoukankan      html  css  js  c++  java
  • 08-spring整合 junit

    一、spring整合 junit 问题解析

    1. 应用程序的入口
      • main 方法
    2. Junit单元测试中,没有 main 方法也能执行
      1. junit 集成了一个 main 方法
      2. 该方法就会判断当前测试类中那些方法有 @Test 注解
      3. junit 就让有 Test 注解的方法执行
    3. junit 不会管我们是否采用 spring 框架
      1. 在执行测试方法时,junit根本不知道我们是不是使用了 spring 框架
      2. 所以也就不会为我们读取配置文件/配置类创建 spring 核心容器
    4. 由以上三点可知
      • 当测试方法·执行时,没有 IOC 容器,就算写了 Autowired 注解,也无法实现注入

    二、Spring 整合 junit 的配置

    1.加入架包

            <!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-test</artifactId>
                <version>5.1.9.RELEASE</version>
                <scope>test</scope>
            </dependency>
    

    2.@Runwith

    使用 Junit 提供的一个注解把原来的 main 方法替换了,替换成 spring 提供的

    这里面要求的是一个字节码,必须是继承 Runner 这个类

    3.@ContextConfiguration

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

    • @ContextConfiguration
      • locations:指定 xml 文件的位置,加上 classpath 关键字,表示在类路径下
      • classes:指定注解类所在地理位置
    • 注意:当我们使用 spring 5.x 版本的时候,要求 Junit 的 jar 必须是 4.12 及以上
    package com.test;
    
    import com.config.JdbcConfig;
    import com.config.SpringConfiguration;
    import com.domain.Account;
    import com.service.IAccountService;
    import org.junit.Before;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.annotation.AnnotationConfigApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    import org.springframework.test.context.ContextConfiguration;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    
    import java.util.List;
    
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(classes = SpringConfiguration.class)
    public class AccountServiceTest {
    
        @Autowired
        IAccountService as=null;
    
    
        @Test
        public void testFindAllAccount(){
            //3.执行方法
            List<Account> accounts = as.findAllAccount();
            for (Account account:accounts){
                System.out.println(account);
            }
        }
    
    }
    
    
  • 相关阅读:
    第七十一课 图的定义与操作
    第七十课 二叉树经典面试题分析
    第六十九课 二叉树的线索化实现
    第六十八课 二叉树的比较与相加
    第六十七课 二叉树的典型遍历方式
    第六十六课 二叉树结构的层次遍历
    第六十五课 二叉树中属性操作的实现
    2018华为笔试题
    交错01串
    操作序列(网易)
  • 原文地址:https://www.cnblogs.com/zuiren/p/11437518.html
Copyright © 2011-2022 走看看