2012-06-05 38 views
4

我正在爲OpenEJB 3.1.3正確配置數據源的問題。我嘗試配置連接到postgres數據庫,但是我調試測試我得到默認的hsql連接參數。OpenEJB - 爲JUnit配置數據源

這裏是我的測試類:

@RunWith(ApplicationComposer.class) 
public class OpenEJBTest { 
    @EJB 
    Files fb; 

    @Test 
    public void testSth() { 
     List<UploadSession> uploadNotFinishedSessions = fb.getUploadNotFinishedSessions(); 
    } 

    @Module 
    public EjbJar beans() { 
     EjbJar ejbJar = new EjbJar("beans"); 
     ejbJar.addEnterpriseBean(new StatelessBean(FilesBean.class)); 
     ejbJar.addEnterpriseBean(new StatelessBean(FilesUtilBean.class)); 
     ejbJar.addEnterpriseBean(new StatelessBean(ServerFilesBean.class)); 
     ejbJar.addEnterpriseBean(new StatelessBean(UserUtilBean.class)); 
     return ejbJar; 
    } 

    @Module 
    public PersistenceUnit persistence() { 
     PersistenceUnit unit = new PersistenceUnit("postgresPU", HibernatePersistence.class.getName()); 
     String simpleXml = SimpleXmlUtil.toSimpleXml(unit); 
     System.out.println(simpleXml); 
     unit.setJtaDataSource("PostgresDS"); 
     unit.setNonJtaDataSource("PostgresDSUnmanaged"); 
     return unit; 
    } 
} 

我想:

  1. 添加jndi.properties到類路徑:
postgresPU=new://Resource?type=DataSource 
postgresPU.JdbcDriver=org.postgresql.Driver 
postgresPU.JdbcUrl=jdbc:postgresql:/localhost:5433/pdb 
postgresPU.JtaManaged=true 
postgresPU.DefaultAutoCommit=false 
postgresPU.UserName=... 
    通過openejb.xml個
  1. 配置數據源(位於classpath中)
<Resource id="PostgresDS" type="DataSource"> 
    JdbcDriver org.postgresql.Driver 
    JdbcUrl jdbc:postgresql://localhost:5433/pdb 
    UserName user 
    Password pass 
    JtaManaged true 
</Resource> 

<Resource id="PostgresDSUnmanaged" type="DataSource"> 
    JdbcDriver org.postgresql.Driver 
    JdbcUrl  jdbc:postgresql://localhost:5433/pdb 
    UserName user 
    Password pass 
    JtaManaged false 
</Resource> 

但無論是它的工作原理 - 數據源沒有被配置可言,數據源的默認版本仍然存在。 因爲默認的HSQL連接我獲得以下錯誤:

WARN - SQL Error: -22, SQLState: S0002 
ERROR - Table not found in statement [select top ? user0_.id as col_0_0_ from tusers user0_ where user0_.login=?] 

什麼我可能做錯了嗎?

回答

5

ApplicationComposer不使用JNDI來引導容器,因此jndi.properties文件是從未見過的。

你可以做的是在方法上使用org.apache.openejb.junit.Configuration註釋,讓它返回你想用來配置測試的屬性。

@Configuration 
public Properties properties() { 
    //... 
} 

我會重新命名jndi.properties到別的東西,所以它不是混亂,那麼你可以使用這樣的代碼來發現它在類路徑中。

final URL url = this.getClass().getResource("/config.properties"); 
    final Properties props = new Properties(); 
    final InputStream in = url.openStream(); 
    try { 
     props.load(in); 
    } finally { 
     close(in); 
    }