扫码一下
查看教程更方便
现在我们将应用简单的例子来一步一步教你如何使用 junit。
@test(excepted=xx.class): xx.class 表示异常类,表示测试的方法抛出此异常时,认为是正常的测试通过的 @test(timeout = 毫秒数) :测试方法执行时间是否符合预期在c:\ > junit_workspace 路径下创建一个名为 messageutil.java 的类用来测试。
messageutil.java/* * this class prints the given message on console. */ public class messageutil { private string message; //constructor //@param message to be printed public messageutil(string message){ this.message = message; } // prints the message public string printmessage(){ system.out.println(message); return message; } }
testprintmessage() 的方法。annotaion @test。在c:\ > junit_workspace路径下创建一个文件名为 testjunit.java 的类
testjunit.javaimport org.junit.test; import static org.junit.assert.assertequals; public class testjunit { string message = "hello world"; messageutil messageutil = new messageutil(message); @test public void testprintmessage() { assertequals(message,messageutil.printmessage()); } }
junitcore 类的 runclasses 方法来运行上述测试类的测试案例getfailures() 方法中的失败结果wassuccessful() 方法中的成功结果在 c:\ > junit_workspace 路径下创建一个文件名为 testrunner.java 的类来执行测试案例
testrunner.javaimport org.junit.runner.junitcore; import org.junit.runner.result; import org.junit.runner.notification.failure; public class testrunner { public static void main(string[] args) { result result = junitcore.runclasses(testjunit.class); for (failure failure : result.getfailures()) { system.out.println(failure.tostring()); } system.out.println(result.wassuccessful()); } }
用 javac 编译 messageutil 、test case 和 test runner 类。
c:\junit_workspace>javac messageutil.java testjunit.java testrunner.java
现在运行 test runner ,它可以运行在所提供的 test case 类中定义的测试案例。
c:\junit_workspace>java testrunner
检查运行结果
hello world
true
现在更新 c:\ > junit_workspace 路径下的 testjunit,并且检测失败。改变消息字符串。
testjunitimport org.junit.test; import static org.junit.assert.assertequals; public class testjunit { string message = "hello world"; messageutil messageutil = new messageutil(message); @test public void testprintmessage() { message = "new word"; assertequals(message,messageutil.printmessage()); } }
让我们保持其他类不变,再次尝试运行相同的 test runner
test runnerimport org.junit.runner.junitcore; import org.junit.runner.result; import org.junit.runner.notification.failure; public class testrunner { public static void main(string[] args) { result result = junitcore.runclasses(testjunit.class); for (failure failure : result.getfailures()) { system.out.println(failure.tostring()); } system.out.println(result.wassuccessful()); } }现在运行在 test case 类中提供的即将运行测试案例的 test runner
c:\junit_workspace>java testrunner
检查运行结果
hello world
testprintmessage(testjunit): expected:<[new wor]d> but was:<[hello worl]d>
false