利用JUnit和Spring-test对SpringJDBC组件DAO层测试

借着学习Druid连接池的机会,使用的Spring,将知识点联系起来,简单写了一个利用JUnit和Spring-test对SpringJDBC组件DAO层测试的Demo,分类归在Spring中吧。

 

SpringJDBC组件是Spring提供的一个对底层JDBC的封装,扩展了更多更方便的接口,方便我们对数据库的操作。

 

Demo利用Maven构建,pom.xml文件配置如下(Tomcat、Jetty等暂时不需要,懒得删...)

 

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.zhangpl.demo</groupId>
	<artifactId>druid</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>

	<name>druid</name>
	<url>http://maven.apache.org</url>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<!-- 如果依赖的version,使用${druid-version},则需要定义properties属性 -->
		<druid-version>1.0.2</druid-version>
	</properties>


	<dependencies>
		<!-- druid -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid</artifactId>
			<version>${druid-version}</version>
			<!-- <version>0.2.8</version> -->
		</dependency>


		<!-- Servlet、JSP -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.4</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>jsp-api</artifactId>
			<version>2.0</version>
			<scope>provided</scope>
		</dependency>

		<!-- Junit -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.9</version>
		</dependency>

		<!-- Mysql -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.9</version>
		</dependency>

		<!-- commons-logging -->
		<dependency>
			<groupId>commons-logging</groupId>
			<artifactId>commons-logging</artifactId>
			<version>1.2</version>
			<type>pom</type>
		</dependency>

		<!-- Spring-test -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>3.2.5.RELEASE</version>
		</dependency>

		<!-- Spring相关 -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>3.2.5.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</artifactId>
			<version>3.2.5.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aop</artifactId>
			<version>3.2.5.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>3.2.5.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context-support</artifactId>
			<version>3.2.5.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>3.2.5.RELEASE</version>
		</dependency>

	</dependencies>

	<build>
		<plugins>

			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<source>1.6</source>
					<target>1.6</target>
				</configuration>
			</plugin>

			<plugin>
				<groupId>org.mortbay.jetty</groupId>
				<artifactId>jetty-maven-plugin</artifactId>
				<version>8.1.15.v20140411</version>
				<configuration>
					<scanIntervalSeconds>10</scanIntervalSeconds>
				</configuration>
			</plugin>

			<plugin>
				<groupId>org.codehaus.cargo</groupId>
				<artifactId>cargo-maven2-plugin</artifactId>
				<version>1.4.8</version>
				<configuration>
					<container>
						<containerId>tomcat7x</containerId>
						<home>E:\SoftwareDevelopment\Software\apache-tomcat\apache-tomcat-7.0.47-windows-x64\apache-tomcat-7.0.47</home>
					</container>
					<configuration>
						<type>standalone</type>
						<home>${project.build.directory}/tomcat7x</home>
						<properties>
							<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
							<cargo.servlet.URIEncoding>UTF-8</cargo.servlet.URIEncoding>
							<cargo.jvmargs>-Dfile.encoding=UTF-8</cargo.jvmargs>
						</properties>
					</configuration>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

 

 

然后,数据库中建表users,字段很简单,对应下面的实体类User.java

 

/**
 * @author zhangpl
 * E-mail:[email protected]
 * 2014年8月24日  下午11:34:27
 */
public class User {
	private int id;
	private String username;
	private String password;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	
}

 

 

下面是Spring的配置文件applicationContext.cml,注意:

1.连接池使用的是Druid,可不与理会;

2.使用Spring提供的注解;

3.扫描属性文件的配置;

 

<?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:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">

	<!-- 注解配置 -->
	<context:component-scan base-package="com.zhangpl.demo" />
	<!-- 扫描属性文件 -->
	<context:property-placeholder location="classpath*:db.properties" />

	<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
		init-method="init" destroy-method="close">
		<!-- 基本属性 url、user、password -->
		<property name="url" value="${jdbc.url}" />
		<property name="username" value="${jdbc.user}" />
		<property name="password" value="${jdbc.password}" />

		<!-- 配置初始化大小、最小、最大 -->
		<property name="initialSize" value="1" />
		<property name="minIdle" value="1" />
		<property name="maxActive" value="20" />

		<!-- 配置获取连接等待超时的时间 -->
		<property name="maxWait" value="60000" />

		<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
		<property name="timeBetweenEvictionRunsMillis" value="60000" />

		<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
		<property name="minEvictableIdleTimeMillis" value="300000" />

		<property name="validationQuery" value="SELECT 'x'" />
		<property name="testWhileIdle" value="true" />
		<property name="testOnBorrow" value="false" />
		<property name="testOnReturn" value="false" />

		<!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->
		<property name="poolPreparedStatements" value="false" />
		<property name="maxPoolPreparedStatementPerConnectionSize"
			value="20" />

		<!-- 配置监控统计拦截的filters -->
		<property name="filters" value="stat" />
	</bean>

	<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
		<property name="dataSource">
			<ref bean="dataSource" />
		</property>
	</bean>

</beans>

 

 

UserDAO.java

 

/**
 * @author zhangpl
 * @E-mail [email protected]
 * @Date   2014年8月24日  下午11:30:13
 */
@Repository
public class UserDAO {

	@Resource
	private JdbcTemplate jdbcTemplate;
	
	/**
	 * 查询
	 * Edited by zhangpl
	 * @return List<Map<String,Object>>
	 */
	public List<Map<String,Object>> getUser(){
		List<Map<String ,Object>> userList = this.jdbcTemplate.queryForList("select *from users");
		return userList;
	}
	
	/**
	 * 添加
	 * Edited by zhangpl
	 * @param user
	 * @return int
	 */
	public int saveUser(User user){
		int flag = this.jdbcTemplate.update("insert into users(username,password) values ('"+user.getUsername()+"','"+user.getPassword()+"') ");
		return flag;
	}
	
	/**
	 * 删除
	 * Edited by zhangpl
	 * @param id
	 * @return int
	 */
	public int deleteUser(int id){
		int flag = this.jdbcTemplate.update("delete from users where id = "+id);
		return flag;
	}
	
	/**
	 * 修改
	 * Edited by zhangpl
	 * @param user
	 * @return int
	 */
	public int updateUser(User user){
		int flag = this.jdbcTemplate.update("update users set username='"+user.getUsername()+"',password='"+user.getPassword()+"' where id="+user.getId());
		return flag;
	}

	
}

 

 

建立测试类UserDAOTest.java

 

/**
 * @author zhangpl
 * @E-mail [email protected]
 * @Date   2014年8月28日  下午10:56:58
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath*:applicationContext.xml"})
public class UserDAOTest {
	
	@Resource
	UserDAO userDAO;
	
	@Test
	public void testGetUser() throws Exception {
		List list = userDAO.getUser();
		System.out.println(list);
	}
	
	@Test
	public void testSaveUser() throws Exception {
		User user = new User();
		user.setUsername("zhangsan");
		user.setPassword("123456");
		int flag = userDAO.saveUser(user);
		if(flag>0){
			System.out.println("添加成功!");
		}else{
			System.out.println("添加失败");
		}
	}
	
	@Test
	public void testUpdateUser() throws Exception {
		User user = new User();
		user.setId(2);
		user.setUsername("zhangxingsan");
		user.setPassword("654321");
		int flag = userDAO.updateUser(user);
		if(flag>0){
			System.out.println("修改成功!");
		}else{
			System.out.println("修改失败!");
		}
	}
	
	@Test
	public void testDeleteUser() throws Exception {
		int flag = userDAO.deleteUser(2);
		if(flag>0){
			System.out.println("删除成功!");
		}else{
			System.out.println("删除失败!");
		}
	}
}

 

 

测试类中需要注意的地方:

@RunWith:指定单元测试执行类,这里就指定的是SpringJUnit4ClassRunner.class;

@ContextConfiguration:指定Spring的配置文件;

 

记下来是对知识点的一个小结,有不当的地方,欢迎批评指正。

你可能感兴趣的:(测试,JUnit,SpringJDBC,DAO层)