1. 測試類不需要extends TestCase,代之以annotation,即測試類(不需要extends TestCase)的方法只要有@Test就可以了
2. 測試方法命名不需要一定要以test開頭
public class Unit {
private int data;
public Unit(int data){
this.data = data;
}
public boolean test(){
return true;
}
public boolean equals(Object o){
if(o instanceof Unit){
return ((Unit)o).data == data;
}
return false;
}
public void exception(){
if (this.data==0)
throw new IndexOutOfBoundsException("exception in Unit");
}
}
可以用eclipse自動生成測試類,選中要測試的類,然後new -junit test case
測試類:
import org.junit.*;
public class UnitTest {
private Unit unit1 = new Unit(1);
private Unit unit2 = new Unit(2);
@BeforeClass
public static void setUpBeforeClass() throws Exception {
System.out.println("setUpBeforeClass");
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
System.out.println("tearDownAfterClass");
}
@Before
public void setUp() throws Exception {
System.out.println("setUp");
}
@After
public void tearDown() throws Exception {
System.out.println("tearDown");
}
@Test
public void notestTest() { // 方法名不以test開頭
//fail("Not yet implemented");
Assert.assertTrue(unit1.test());
}
@Test
public void testEqualsObject() {
//fail("Not yet implemented");
Assert.assertEquals(unit1, new Unit(1));
Assert.assertEquals(unit1, unit2);
}
@Test(expected = IndexOutOfBoundsException.class)
public void testException() {
//fail("Not yet implemented");
new Unit(0).exception();
}
}
測試結果如下
爲了進行TestSuit,再增加一個testcase
public class Unit2 {
public boolean test(){
return true;
}
}
import org.junit.Test;
public class Unit2Test {
@Test
public void testTest() {
//fail("Not yet implemented");
org.junit.Assert.assertTrue(new Unit2().test());
}
}
==================================================================================
增加一個TestSuit(使用ecilpse的new -junit Test Suit只能找到3.x風格的extends TestCase的測試類,不知爲何)
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
@RunWith(Suite.class)
@SuiteClasses( { UnitTest.class, Unit2Test.class })
public class Suit {
}
TestSuit測試結果
以下是控制檯輸出信息,跟測試類的各種annotation有關
=====================================================================================