环境:win7+eclipse+jdk1.7+junit4
1.环境配置
项目下新建lib文件夹
将juint4.12 复制进lib目录下
右键--build path--config build path--libraries--add jars--junit-4.12.jar
2.项目结构
项目
--src
--package
--class
--testpackage
--testclass
--lib
--junit4.12.jar
--build.xml
3.代码
Sample.java
package testjunitsample;
public class Sample {
public int add(int x,int y){
return x+y;
}
public int sub(int x,int y){
return x-y;
}
}
TestSample.java
package testjunitsample;
import junit.framework.TestCase;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class TestSample extends TestCase {
private Sample sp ;
@Before
public void setUp() throws Exception {
sp = new Sample();
System.out.println("init.....");
}
@Test
public void testAdd(){
int y = sp.add(1, 2);
Assert.assertEquals(3, y);
}
@Test
public void testSub(){
int z= sp.sub(4, 2);
Assert.assertEquals(2, z);
}
}
build.xml
<?xml version="1.0" encoding="UTF-8"?>
<project name="testjuintsample" default="testsuite">
<property name="project.name" value="testjunitsample" />
<property name="src.dir" value="src"/>
<property name="lib.dir" value="lib"/>
<property name="tests.dir" value="tests"/>
<property name="target.dir" value="target"/>
<property name="classes.dir" value="${target.dir}/classes"/>
<property name="junit.out.dir.xml" value="${target.dir}/report/junit/xml"/>
<property name="junit.out.dir.html" value="${terget.dir}/report/junit/html"/>
<echo>cleaning dirs ......</echo>
<target name="clean" description="delete the earlier classes">
<delete dir="${target.dir}" quiet="yes"></delete>
</target>
<echo>make the require dirs</echo>
<target name="makedir" depends="clean" description="make the require dirs">
<mkdir dir="${classes.dir}"/>
</target>
<echo>compile......</echo>
<target name="compile" depends="makedir" description="compile the src">
<javac debug="true" destdir="${classes.dir}">
<src path="${src.dir}"/>
<src path="${tests.dir}"/>
<classpath>
<fileset dir="${lib.dir}" includes="**/**.jar"/>
</classpath>
</javac>
</target>
<path id="classpath.test">
<path path="${java.class.path}"/>
<pathelement location="${classes.dir}"/>
<fileset dir="${lib.dir}" includes="**/**.jar"/>
<path location="${classes.dir}"></path>
</path>
<echo>running the juint case test......</echo>
<target name="testsuite" depends="compile" description="test the juint case">
<delete dir="${junit.out.dir.xml}"/>
<mkdir dir="${junit.out.dir.xml}"/>
<junit printsummary="yes" fork="true" haltonfailure="yes">
<classpath refid="classpath.test"/>
<sysproperty key="ant.home" value="${ant.home}"/>
<formatter type="xml"/>
<batchtest fork="yes" todir="${junit.out.dir.xml}">
<fileset dir="${classes.dir}" includes="**/Test**.class"/>
</batchtest>
</junit>
</target>
</project>
4.运行结果