一、各种断言
1、assertEquals([String message], expected, actual)//判断相等
assertEquals([String message], expected, actual, tolerance)//判断相等,tolerance指经度,比如0.01指小数点后两位
2、assertNull([String message], java.lang.Object object)
assertNotNull([String message], java.lang.Object object)
3、assertSame([String message], expected, actual)//判断是否为同一个对象
assertNotSame([String message], expected, actual)
4、assertTrue([String message], boolean condition)
assertFalse([String message], boolean condition)
5、fail([String message])//此断言使测试立即失败,通常用于标记某个不应该被到达的分支
二、JUnit框架
例子:
-----------------------------------------------
//被测试类TSP
package test;
public class TSP {
public int shortestPath(int numCities) {
// Ha! Mock object!
switch (numCities) {
case 50: return 2300;
case 5: return 140;
case 10: return 586;
}
return 0;
}
public void loadCities(String name) {
}
public void releaseCities() {
}
}
-----------------------------------------------
//测试类TestClass
package test;
import junit.framework.*;
public class TestClass extends TestCase {
private static TSP tsp;
public TestClass(String method) {
super(method);
}
protected void setUp(){
tsp = new TSP();
System.out.println("per-test set up");
tsp.loadCities("Beijing");
}
protected void tearDown(){
System.out.println("per-test tear down");
tsp.releaseCities();
}
// This one takes a few hours...
public void testLongRunner() {
assertEquals(2300, tsp.shortestPath(50)); // top 50
}
public void testShortTest() {
assertEquals(140, tsp.shortestPath(5)); // top 5
}
public void testAnotherShortTest() {
assertEquals(586, tsp.shortestPath(10)); // top 10
}
//有异常抛出时,会自动中止方法,并报错
public void testException() throws Exception{
throw new Exception() ;
}
//第一种,注释两个suite方法、setUp2、tearDown2
//第二种,注释第二个suite方法
// public static Test suite() {
// TestSuite suite = new TestSuite();
// suite.addTest(
// new TestClass("testShortTest"));
// suite.addTest(
// new TestClass("testAnotherShortTest"));
// return suite;
// }
//第三种,注释第一个suite方法
// public static Test suite() {
// TestSuite suite = new TestSuite();
// suite.addTest(
// new TestClass("testShortTest"));
// suite.addTest(
// new TestClass("testAnotherShortTest"));
// suite.addTest(new TestClass("testException"));
// TestSetup wrapper = new TestSetup(suite){
// protected void setUp(){
// setUp2();
// }
// protected void tearDown(){
// tearDown2();
// }
// };
// return wrapper;
// }
// private static void setUp2(){
// tsp = new TSP();
// System.out.println("per-test set up");
// tsp.loadCities("Beijing");
// }
//
// private static void tearDown2(){
// System.out.println("per-test tear down");
// tsp.releaseCities();
// }
}
三、自定义JUnit断言
自定义的测试都应该继承自自定义的测试类,因为这样可以很容易的加入所有测试类都需要的方法。
eg:
import junit.framework.*;
public class MyTestCase extends TestCase {
public void assertEvenDollars(String message, Money amount) {
assertEquals(message, amount.asDouble() - (int)amount.asDouble(), 0.0, 0.001);
}
public void assertEvenDollars(Money amount) {
assertEvenDollars("", amount);
}
}