代码之家  ›  专栏  ›  技术社区  ›  Premraj

JUnit测试用例与获取db连接以及play框架、spring-jdbctemplate有关的问题?

  •  0
  • Premraj  · 技术社区  · 12 年前

    我在写 JUnit测试用例 ,其中尝试获取DataSource的进程正在获取以下错误消息。

    堆栈跟踪:

       java.lang.NullPointerException
        at play.api.db.DB$.getDataSource(DB.scala:141)
        at play.api.db.DB.getDataSource(DB.scala)
        at play.db.DB.getDataSource(DB.java:22)
        at dao.BaseDao.getJdbcTemplate(BaseDao.java:13)
    

    在这里,我使用了spring-jdbctemplate、play框架和JUnit。 请找到我正在使用的以下资源文件。

    应用程序.conf

    db.default.jndiName=DefaultDS
    db.default.driver=oracle.jdbc.driver.OracleDriver
    db.default.url="jdbc:oracle:thin:@//xx.xx.xx.xx:1521/XE"
    db.default.user=work
    db.default.pass=work
    ......
    

    组件.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
        xmlns:jee="http://www.springframework.org/schema/jee"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
             http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
             http://www.springframework.org/schema/context
             http://www.springframework.org/schema/context/spring-context-3.0.xsd 
             http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd">
    
        <context:component-scan
            base-package="controllers,services,dao,org.springframework.jndi" />
    
    </beans>
    

    基本道.java

    package dao;
    
    import org.springframework.jdbc.core.JdbcTemplate;
    
    import play.db.DB;
    
    public class BaseDao {
    
        private JdbcTemplate jdbcTemplate;
    
        public JdbcTemplate getJdbcTemplate() {
            if (jdbcTemplate == null) {
                this.jdbcTemplate = new JdbcTemplate(DB.getDataSource("default"));
            }
            return this.jdbcTemplate;
        }
    
        public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
            this.jdbcTemplate = jdbcTemplate;
        }
    
    }
    

    PublishedReferenceYieldServiceImplTest.java

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration("classpath:components.xml")
    public class PublishedReferenceYieldServiceImplTest {
    //Here I am accessing baseDAO
    ...
    }
    
    1 回复  |  直到 10 年前
        1
  •  1
  •   asparagus    12 年前

    似乎您缺少加载应用程序的上下文。检查play.test.Helpers包。

    尝试将实际测试代码放入以下块中:

    running(fakeApplication(), new Runnable() {
        @Override
        public void run() {
            ...your test here...
        }           
    });