Spring mvc3 application test environment setup
-
29-06-2021 - |
Pregunta
I am working under a spring mvc3 application.
And I meet some problem when I want to do some unit test for the Dao component.
This is my application structure in eclipse:
application
build
classes
src
org.....
res
jdbc.properties
log4j.properties
www
resources
css
js
WEB-INF
mybatis
config.xml
view
spring
servlet-context.xml
spring-contex.xml
spring-dao.xml
web.xml
servlet-context.xml:
<!-- web related config omitted -->
<import resource="spring-context.xml" />
<import resource="spring-dao.xml" />
spring-context.xml:
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">.......</bean>
<context:property-placeholder location="classpath*:jdbc.properties" />
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="/WEB-INF/mybatis/config.xml" />
</bean>
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory" />
</bean>
spring-dao.xml:
<bean id="postDao" class="com.king.dao.PostDao" />
And this is my PostDao class:
public class PostDao extends SqlSessionDaoSupport{
public Post query(int id) {
return getSqlSession().selectOne("com.king.model.PostMapper.selectById", id);
}
}
The above configuration works well in the servlet container.
However when I want to test the PostDao without in the servlet environment,I meet some problems.
I tried this:
public static main(String[] args){
ApplicationContext ctx = new ClassPathXmlApplicationContext("E:/application/www/WEB-INF/spring/servlet-context.xml");
PostDao pd = (PostDao) ctx.getBean("postDao");
Post p = pd.query(9);
}
Then I get the error, the "mybatis/config.xml" can not be founded.
I know this is caused by the different running environment.
In servlet context,spring will find the "/WEB-INF/mybatis/config.xml",but when in a java application,it can not find it.
So I wonder how can I make my testing work?
Solución
Do you mean unit or integration testing? If so, I'd recommend using the Spring Test module - it allows you to define a specific test context where you can provide real or mocked implementations of the relevant beans. It integrates well with JUnit and provides a lot of the scaffolding you need to successfully run tests within a Spring environment.