1、常用的註解,代碼示例:
package test.demo;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before; import org.junit.BeforeClass;
import org.junit.Test;
public class JunitDemo {
private String str;
@BeforeClass //使用該註解的方法,表示在實例化整個類之前執行一次
public static void beforeClass(){
}
@AfterClass //使用該註解的方法,表示在實例化整個類之後執行一次
public static void afterClass(){
}
@Before //使用該註解的方法,表示在執行Test方法之前執行一次
public void setUp(){
}
@After //使用該註解的方法,表示在執行Test方法之後執行一次
public void tearDown(){
}
@Test //使用該註解的方法,表示要執行的測試方法
public void test(){}
@Ignore("this test has not implemented ")
@Test //使用Ignore表示此測試方法忽略不執行,也可以指定string消息,指示原因
public void hello(){}
@Test(expected=MyException.class) //Test中的expected選項是期望有一個MyException異常拋出,如果沒有拋出執行失敗
public void Demo() throws MyException{
throw new MyException("hello exception");
}
@Test(timeout=5000) //Test中timeout選項是限時執行,以毫秒爲單位,如果超出還沒有執行完則報timeout錯誤
public void timeout(){
int i=0;
while(i < 3){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
i++;
System.out.println(str);
}
}
}
class MyException extends Exception{
private static final long serialVersionUID = 1L;
super(message);
}
}