• spring-test使用介绍


    一、首先引入spring的jar文件到项目中,我采用maven管理项目依赖的jar包:

    <properties>
        <spring.version>4.0.0.RELEASE</spring.version>
    </properties>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>${spring.version}</version>
    </dependency>    

    项目目录结构如下:

    还需要在项目中引入junit4的jar包

    二、编写测试类

      上图结构中的JDBCTransactionTest.java为测试类其部分代码如下:

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations = "classpath:applicationContext_jdbc_transaction.xml")
    public class JDBCTransactionTest extends AbstractJUnit4SpringContextTests {
        @Test
        public void transactionTest() throws ClassNotFoundException,
                InstantiationException, IllegalAccessException, SQLException {
            Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
            String url = "jdbc:oracle:thin:@localhost:1521:xxxxxxxx";
            String user = "xxxxxxx";
            String password = "xxxx";
            Connection conn = null;
            Statement statement = null;
            try {
                conn = DriverManager.getConnection(url, user, password);
                conn.setAutoCommit(false);
                statement = conn.createStatement();
                String sql = "insert into user_base values(1,'james','aaa',2,12)";
                statement.executeUpdate(sql);
                conn.commit();
    
            } catch (SQLException e) {
                if (conn != null)
                    conn.rollback();
                conn.close();
                statement.close();
            }
        }
    }

      要求:该类必须继承自AbstractJUnit4springcontextTests 

         然后在其中编写方法,并在方法上加注释:@Test

           在类的上部添加注释:
            @RunWith(SpringJUnit4ClassRunner.class)
              @ContextConfiguration(locations = "classpath:applicationContext.xml")

    这样便可以通过配置spring配置文件的位置进行测试开发了。

    三、测试类中获取IOC容器

      在AbstractJUnit4springcontextTests 中有定义applicationContext变量,就是spring的全局IOC容器,通过它可以获取在xml中定义的bean

      为了通过名字方便获取自定义的bean,我们可以将该applicationContext封装到方法内,通过给定的bean的名称向外部提供自定义的bean,也可以提供给外部applicationContext:

    public Object getBean(String beanName) {
        return applicationContext.getBean(beanName);
    }
    
    protected ApplicationContext getContext() {
        return applicationContext;
    }
  • 相关阅读:
    MapKit 大头针基本使用
    iOS获取文件的大小
    iOS截取图片方法
    iOS通知3种使用方法
    iOS12适配及兼容问题解决,xcode10问题
    Mac不使用iTunes导出照片
    Xcode 10 项目迁移 Multiple commands produce...
    tableView在UITableViewStylePlain的状态下取消悬浮效果(取消粘性效果)
    OC 字符串和字典的相互转化
    破解 Mac OS管理员密码 亲测可用
  • 原文地址:https://www.cnblogs.com/brolanda/p/4299699.html
Copyright © 2020-2023  润新知