junit编写spring测试案例
项目结构:
│ pom.xml
│ spring-tomcat-jdbc.iml
│
└─src
├─main
│ ├─java
│ └─resources
│ config.properties
│ spring-context.xml
│
└─test
├─java
│ └─com
│ └─sxz
│ └─zxd
│ BaseTest.java
│ TomcatJdbcTest.java
│
└─resources
config.properties
spring-context.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:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:property-placeholder location="classpath:config.properties"/>
<context:component-scan base-package="com.sxz.zxd"></context:component-scan>
</beans>
注意:运行junit时候,配置文件都是在test/resources下的,classpath:config.properties这里指的是test/resources/config.properties文件
BaseTest.java文件:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {
"classpath*:spring-*.xml"
})
public class BaseTest {
}
注意: 运行junit使用的配置文件都是在test/resources文件夹下的。@ContextConfiguration中写的locatioins是classpath*:spring-*.xml,而不是classpath:spring-*.xml,classpath*:spring-*.xml不仅加载test/resources下的配置文件,而且也会加载java/resources下的配置文件,因为这里的junit使用的spring-context.xml文件和java/resources下的一样,所以复用了java/resources/spring-context.xml文件。如果配置文件加载不正确,可能会发生Bean不能注入的问题
TomcatJdbcTest.java文件:
public class TomcatJdbcTest extends BaseTest {
}
本文介绍了一个使用Spring和Junit进行集成测试的例子。通过在test/resources目录下配置spring-context.xml,并利用BaseTest作为测试基类,实现了对Tomcat JDBC连接池的功能验证。

44

被折叠的 条评论
为什么被折叠?



