日期:2014-05-19  浏览次数:20712 次

用junit测试spring时,加载dataSource出错
1,bean-dao.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" 
  "http://www.springframework.org/dtd/spring-beans.dtd">


<beans>
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="java:comp/env/jdbc/fundmonitor"></property>
</bean>
<beans>
2,测试代码
package com.prhc.fundmonitor.dao.testCase;

import junit.framework.TestCase;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.prhc.fundmonitor.dao.log.LogDao;

public class LogDaoImplTest extends TestCase {

private LogDao logDao;

ApplicationContext context;
protected void setUp() {
context = new ClassPathXmlApplicationContext(
"file:WebRoot\\WEB-INF\\spring\\bean-dao.xml");
}

protected void tearDown() {

}

private LogDao getLogDao() {
if (logDao == null)
// userDao = (UserDao) context.getBean("userDao");
logDao = (LogDao) context.getBean("logDao");
return logDao;
}

@Test
public void testGetNewID() {
int result;
int expect = 69544;
try {
result = getLogDao().getNewID();
this.assertEquals(result, expect);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
3,出错信息
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in URL [file:WebRoot/WEB-INF/spring/bean-dao.xml]: Initialization of bean failed; nested exception is javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial

麻烦各位资深人士。
本人送出所有的分。谢谢!!!

------解决方案--------------------
不能 继承TestCase ,要集成XXXXTestCase,具体我也忘了。
------解决方案--------------------
2楼的搞错了,继承什么都可以,关键是你的ds使用了JNDI,不起服务器就没有这个JNDI,需要用spring-mock一个JNDI