开发者社区> 问答> 正文

spring工程数据源使用的jndi如何junit做测试用例?报错

@Runwith

@ContextConfiguration(locations={"classpath:applicationContext.xml"}) 

applicationContext里面第一个bean就是jndi数据源,测试用例启动就报错找不到对应数据源

参考了这:

https://blog.csdn.net/u012387062/article/details/55224536

也不行,有没有人遇到过啊 

展开
收起
爱吃鱼的程序员 2020-06-06 16:39:08 561 0
1 条回答
写回答
取消 提交回答
  • https://developer.aliyun.com/profile/5yerqm5bn5yqg?spm=a2c6h.12873639.0.0.6eae304abcjaIB
                        <pre>使用jndi数据源,需要依赖容器,所以不直接只用springtest做测试用例,使用junit的before方法绑定jndi.</pre> 
    
    @Before
    public void init() {
        System.out.println("ehcache缓存目录:" + System.getProperty("java.io.tmpdir"));
    
        try {
            ClassPathXmlApplicationContext app = new ClassPathXmlApplicationContext("classpath:spring/springtest/InitJndi.xml");
            DataSource ds = (DataSource) app.getBean("dataSource");
            SimpleNamingContextBuilder builder = new SimpleNamingContextBuilder();
            builder.bind("java:comp/env/jdbc/db1", ds);
            builder.activate();
            System.out.println("java:comp/env/jdbc/OracleDB init success...");
    
            ClassPathXmlApplicationContext appcontext = new ClassPathXmlApplicationContext("classpath:spring/spring.xml");
    
            //这里提取测试bean
            testCacheService = (TestCacheService) appcontext.getBean("testCacheService");
            sqlService = (SqlService) appcontext.getBean("sqlService");
    
            baseDao = (BaseDao) appcontext.getBean("baseDao");
            hibernateTemplate = (HibernateTemplate) appcontext.getBean("hibernateTemplate");
    
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
                            回复 <a class="referer" target="_blank">@tianxia007</a>  : 为何我还是有错
                        
    
                            此方法亲测可用
                        
    
                        <p>你好,请问能否把这两个配置文件贴出来呀</p>
    
    2020-06-06 16:39:27
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
云栖社区特邀专家徐雷Java Spring Boot开发实战系列课程(第20讲):经典面试题与阿里等名企内部招聘求职面试技巧 立即下载
微服务架构模式与原理Spring Cloud开发实战 立即下载
阿里特邀专家徐雷Java Spring Boot开发实战系列课程(第18讲):制作Java Docker镜像与推送到DockerHub和阿里云Docker仓库 立即下载