@DingCao-HJJ
2015-09-03T04:18:29.000000Z
字数 2422
阅读 2819
编程工具/环境 Java junit
先写好要测试的类和用以测试的类,如下:
// HelloWorld.javaimport java.util.*;public final class HelloWorld {private String str;public static void main(String[] args) {HelloWorld hw = new HelloWorld();hw.hello();System.out.println(hw.str);}public void hello() {str = "Hello World!";}public String getStr() {return str;}}
在junit4.x版本中,我们可以用@test来表示一个测试。
// HelloWorldTes.javaimport static org.junit.Assert.*;import org.junit.Test;public class HelloWorldTest {public HelloWorld helloworld = new HelloWorld();@Testpublic void testHello() {helloworld.hello();assertEquals("Hello World!", helloworld.getStr());}}
按照类似的目录组织好文件
/HelloWorld
|-- build.xml
|-- src
|-- HelloWorld.java
|-- HelloWorldTest.java
|-- lib
|-- junit-4.9.jar
|-- build
|-- classes
|-- HelloWorld.class
|-- HelloWorldTest.class
如上,junit的jar包放在了/HelloWorld/lib/文件夹下。
要对HelloWorld进行测试,我们需要用到HelloWorldTest.java, 要先将工作目录转到HelloWord/src/下
cd HelloWord/src
然后进行编译:
HelloWord/src$ javac -classpath .;../lib/junit-4.9.jar HelloWorldTest.java
接下来转到HelloWorld/build/classes目录,运行HelloWorldTest.
HelloWord/src$ cd ../build/classes
HelloWord/src$ java -classpath .;../../lib/junit-4.9.jar org.junit.runner.JUnitCore HelloWorldTest
运行结果:
语法和windows环境类似,只是把命令当中的;替换成:即可。
如下,在build.xml里添加junit的target,并为其设置要引用的变量。注意,这里<junit>下的<classpath>表示目标测试class所在的目录,而再里面的path才表示测试时需要引用的第三方包。
<?xml version="1.0" encoding="UTF-8"?><!-- the only mark of project --><project name="HelloWorld" default="run"><!-- essential properties to refer to --><property name="build.classes.dir" location="build/classes"/><property name="src.dir" location="src" /><property name="lib.dir" location="lib" /><path id="compile.path"><pathelement location="${lib.dir}/junit-4.9.jar" /></path><!-- target is a task, can build, change directory, Junit and so on --><!-- clean up the class files that compiled last time --><target name="clean"><delete dir="${build.classes.dir}" /><mkdir dir="${build.classes.dir}"/></target><target name="compile"><javac srcdir="${src.dir}" destdir="${build.classes.dir}" classpathref="compile.path" includeantruntime="true"></javac></target><!-- auto run after a compilation --><target name="run" depends="clean, compile"><java fork="true" classname="HelloWorld"><classpath path="${build.classes.dir}" /></java></target><!-- tests the methods in HelloWorld.java --><target name="junit" depends="compile"><junit printsummary="true"><classpath path="${build.classes.dir}"><path refid="compile.path" /></classpath><test name="HelloWorldTest" /></junit></target></project>