Ant整合Junit

OS : win7 x64

Ant: 1.9

JDK:1.7


数据库 light

create database if not exists light;

use light;

create table if not exists `user`(
    id  bigint primary key,
    name    varchar(50) not null,
    pass    varchar(50) not null
);



src目录下

User.java

package org.bean;

public class User {
	private Long id;
	private String name;
	private String pass;
	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPass() {
		return pass;
	}
	public void setPass(String pass) {
		this.pass = pass;
	}

    public boolean equals(Object anObject) {
        if (this == anObject) {
            return true;
        }
        if (anObject instanceof User) {
        	User user = (User) anObject;
        	if(user.getName().equals(this.name) &&
        			user.getPass().equals(this.pass) &&
        			user.getId() == this.id){
        		return true;
        	}
        }
        return false;
    }

	public String toString(){
		return "Id:" + id + " Name:" + name + " Pass:" + pass;
	}
}

UserDao.java

package org.dao;

import java.util.List;

import org.bean.User;

public interface UserDao {
	public void save(User user);
	public void update(User user);
	public void delete(User user);
	public User findUserById(Long id);
	public List<User> findAll();
	public Long getMaxId();
}

UserDaoImpl.java

package org.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.bean.User;
import org.dao.UserDao;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

public class UserDaoImpl extends JdbcTemplate implements UserDao {

	private User getUserFromResultSet(ResultSet rs) throws SQLException{
		User user = new User();
		long id = rs.getLong(1);
		String name = rs.getString(2);
		String pass = rs.getString(3);
		
		user.setId(id);
		user.setName(name);
		user.setPass(pass);
		return user;
	}
	
	@SuppressWarnings("deprecation")
	public Long getMaxId(){
		String sql = "select count(id) from `user`";
		return ((long)this.queryForInt(sql));
	}
	
	@Override
	public void save(User user) {
		Long maxID = this.getMaxId();
		String sql = "insert into user(id, name, pass) values(?,?,?)";
		Long id = maxID + 1;
		user.setId(id);
		Object[] objs = {user.getId(), user.getName(), user.getPass()};
		this.update(sql, objs);
	}

	@Override
	public void update(User user) {
		String sql = "update `user` set name=?, pass=? where id=?";
		Object[] objs = {user.getName(), user.getPass(), user.getId()};
		this.update(sql, objs);
 	}

	@Override
	public void delete(User user) {
		String sql = "delete from `user` where id=?";
		Object[] objs = {user.getId()};
		this.update(sql, objs);
	}

	@Override
	public User findUserById(Long id) {
		String sql = "select * from `user` where id = " + id;
		System.out.println(sql);
		List<User> list = this.getUsersFromSql(sql);
		System.out.println("size:" + list.size());
		for(User user : list){
			System.out.println(user);
		}
		
		if(list.size() == 0){
			return null;
		}else{
			return list.get(0);
		}
	}

	@Override
	public List<User> findAll() {
		String sql = "select * from `user`";
		List<User> list = this.getUsersFromSql(sql);
		return list;
	}

	private List<User> getUsersFromSql(String sql){
		List<User> list = this.query(sql, new RowMapper<User>(){
			@Override
			public User mapRow(ResultSet rs, int count) throws SQLException {
				User user = getUserFromResultSet(rs);
				return user;
			}
		});
		return list;
	}
}
ApplicationContext.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:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
	
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
		<property name="driverClassName">
			<value>org.gjt.mm.mysql.Driver</value>
		</property>
		
		<property name="url">
			<value>jdbc:mysql://127.0.0.1:3306/light</value>
		</property>
		
		<property name="username">
			<value>root</value>
		</property>
		
		<property name="password">
			<value>tester</value>
		</property>

	</bean>

    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource">
            <ref local="dataSource"/>
        </property>
    </bean>

    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"
        depends-on="dataSource">
        <property name="dataSource">
            <ref local="dataSource" />
        </property>
    </bean>
    
    <bean id="userDao" class="org.dao.impl.UserDaoImpl" depends-on="jdbcTemplate" scope="prototype">
        <property name="dataSource">
            <ref local="dataSource" />
        </property>
    </bean> 
    
</beans>

test目录

DaoBase.java

package org.dao.impl;

import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.sql.DataSource;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
@TransactionConfiguration(transactionManager="transactionManager",defaultRollback=true)
@Transactional

public class DaoBase extends AbstractTransactionalJUnit4SpringContextTests{
/*
    @Override
    @Resource(name = "dataSource")
    public void setDataSource(DataSource dataSource) {
        super.setDataSource(dataSource);
    }
*/
}

TestUserDaoImpl.java

package org.dao.impl;

import java.util.List;

import javax.annotation.Resource;

import org.bean.User;
import org.dao.UserDao;
import org.junit.Assert;
import org.junit.Test;

public class TestUserDaoImpl extends DaoBase {
	@Resource
	private UserDao userDao;

	@Test
	public void testGetMaxID(){
		Assert.assertEquals(Long.valueOf(2), userDao.getMaxId());
	}

	@Test
	public void testSave(){
		User user = new User();
		String name = "root";
		String pass = "password";
		user.setName(name);
		user.setPass(pass);
		
		userDao.save(user);
		User fuser = userDao.findUserById(3L);
		System.out.println("fuser" + fuser);
		Assert.assertEquals(fuser.getName(), name);
		Assert.assertEquals(fuser.getPass(), pass);
	}

	@Test
	public void testFindByID(){
		Long id = 1l;
		User user = userDao.findUserById(id);
		Assert.assertEquals(user.getName(), "media");
		Assert.assertEquals(user.getPass(), "intel123");
	}
	
	@Test
	public void testFindAll(){
		List<User> list = userDao.findAll();
		for(User user: list){
			System.out.println(user);
		}
	}
	
	@Test
	public void testUpdate(){
		User user = new User();
		user.setId(2l);
		String name = "root";
		String pass = "password";
		
		user.setName(name);
		user.setPass(pass);
		userDao.update(user);
		
		User user2 = userDao.findUserById(2L);
		Assert.assertEquals(user2.getName(), name);
		Assert.assertEquals(user2.getPass(), pass);
		System.out.println(user2.equals(user));
	}
	
	@Test
	public void testDelete(){
		User user = new User();
		user.setId(2l);
		user.setName("root");
		user.setPass("tester");
		
		userDao.delete(user);
		User fuser1 = userDao.findUserById(2L);
		
		Assert.assertNull("fuser2 is null", fuser1);
	}
}

ant build.xml

<?xml version="1.0" encoding="UTF-8"?>
<!-- ====================================================================== 
     Jun 9, 2014 10:13:35 AM                                                        

     project    
     description

     bzhux                                                                
     ====================================================================== -->
<project name="project" default="deploy">
    <description>
            description
    </description>
	
    <property name="src" value="src"/>
    <property name="test" value="test"/>
    <property name="lib" value="WebContent/WEB-INF/lib"/>
    
    <property name="output" value="WebContent/WEB-INF/classes"/>
    <property name="report" value="report"/>
    <property name="report.xml" value="${report}/xml"/>
    <property name="report.html" value="${report}/html"/>
    <property name="TOMCAT_HOME" value="C:\apache-tomcat-7.0.47"/>
    <property name="APP" value="junit"/>

	<path id="classpath">
		<pathelement path="${output}"/>
	    <fileset dir="${lib}">
	        <include name="*.jar"/>
	    </fileset>
	    <fileset dir="${TOMCAT_HOME}/lib">
	        <include name="*.jar"/>
	    </fileset>
	    <fileset dir="${TOMCAT_HOME}/bin">
	        <include name="*.jar"/>
	    </fileset>
<!--
-->
	</path>

    <target name="init">
        <mkdir dir="${output}"/>
        <copy includeemptydirs="false" todir="${output}">
            <fileset dir="${src}">
                <exclude name="**/*.launch"/>
                <exclude name="**/*.java"/>
                <exclude name="**/.svn/**"/>
                <exclude name="**/.git/**"/>
            </fileset>
        </copy>    
    </target>

    <target name="compile" depends="init">
        <javac srcdir="${src}"
         destdir="${output}"
         debug="on"
         includeantruntime="true">
            <classpath refid="classpath"/>
        </javac>

        <javac srcdir="${test}"
         destdir="${output}"
         debug="on"
         includeantruntime="true">
            <classpath refid="classpath"/>
        </javac>
    </target>

	<target name="test" depends="compile">
	  <mkdir dir="${report.xml}"/>
      <junit printsummary="yes" haltοnerrοr="false" showoutput="true" haltonfailure="false">
      	<classpath refid="classpath"/>
      	<formatter type="xml"/>
      	
      	<batchtest fork="true" todir="${report.xml}" haltonfailure="no">
      	    <fileset dir="${test}">
      	       <include name="**/Test*.java"/>
      	    </fileset>
      	</batchtest>
      </junit>
	</target>

	<target name="report" depends="test">
	    <junitreport todir="${report.xml}">
	    	<fileset dir="${report.xml}">
	    		 <include name="TEST-*.xml"/>
	    	</fileset>
	    	<report format="frames" todir="${report.html}"/>
	    </junitreport>
	</target>

    <!-- ================================= 
          target: default  
          includeantruntime="true"            
         ================================= -->
    <target name="deploy" depends="compile">
        <copy todir="${TOMCAT_HOME}/webapps/${APP}">
            <fileset dir="WebContent"/>
        </copy>
    </target>

	<target name="start_tomcat_win" depends="deploy">
		<echo>Launch Tomcat</echo>
		<exec executable="cmd" dir="${TOMCAT_HOME}/bin" failοnerrοr="false">
		    <env key="CATALINA_HOME" path="${TOMCAT_HOME}"/>
			<arg value="/c startup.bat"/> 
		</exec>
	</target>

	<target name="stop_tomcat_win">
        <echo>Shutdown Tomcat</echo>
        <exec executable="cmd" dir="${TOMCAT_HOME}/bin" failοnerrοr="false">
            <env key="CATALINA_HOME" path="${TOMCAT_HOME}"/>
            <arg value="/c shutdown.bat"/> 
        </exec>
	</target>

	<target name="start_tomcat_linux" depends="deploy">
		<echo>Launch Tomcat</echo>
		<exec executable="bash" dir="${TOMCAT_HOME}/bin" failοnerrοr="false">
		    <env key="CATALINA_HOME" path="${TOMCAT_HOME}"/>
			<arg value="startup.sh"/>
		</exec>
	</target>

   <target name="stop_tomcat_linux">
        <echo>Shutdown Tomcat</echo>
        <exec executable="bash" dir="${TOMCAT_HOME}/bin" failοnerrοr="false">
            <env key="CATALINA_HOME" path="${TOMCAT_HOME}"/>
            <arg value="shutdown.sh"/>
        </exec>
    </target>
	
	<target name="tomcat.start" depends="deploy">
	    <java jar="${TOMCAT_HOME}/bin/bootstrap.jar" fork="true">
	    	<classpath refid="classpath"/>
	        <jvmarg value="-Dcatalina.home=${TOMCAT_HOME}"/>
	    </java>
	</target>

	<target name="tomcat.stop">
	   <java jar="${TOMCAT_HOME}/bin/bootstrap.jar" fork="true">
	        <jvmarg value="-Dcatalina.home=${TOMCAT_HOME}"/>
	        <arg line="stop"/>
	   </java>
	</target>

	<target name="tomcat.debug">
		<java jar="${TOMCAT_HOME}/bin/bootstrap.jar" fork="true">
            <jvmarg value="-Dcatalina.home=${TOMCAT_HOME}" />
            <jvmarg value="-Xdebug" />
            <jvmarg value="-Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n" />
		</java>
	</target>

    <target name="clean">
    	  <delete dir="${report}"/>
    	  <delete dir="${output}"/>
    	  <delete dir="${TOMCAT_HOME}/webapps/${APP}"/>
	</target>
</project>





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值