springboot中的spring-test的作用

2 篇文章 0 订阅
1 篇文章 0 订阅



转自:https://www.cnblogs.com/brolanda/p/4299699.html

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;
}
复制代码

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值