Junit是干什么的我在这里就不讲解了。直接开始正题。
常用的注解
Junit中的注解很多,我们首先来看一下最常用的一些注解
- @Test:把一个方法标记未测试方法
- excepted:用来测试异常的,方法抛出该异常说明测试成功
- timeout:用来测试性能的,在规定的时间内完成,说明成功。注意单位是毫秒
- @Before:每个测试方法执行前自动调用一次
- @After:每个测试方法执行完自动调用一次
- @BeforeClass:在类被加载到内存中后执行,这意味着方法需要时static的,并且在构造函数之前执行
- @AfterClass:在类被销毁之前执行,所以需要时static的
- @Ignore:暂不执行该测试方法
下面我们将使用一个简单的例子,将这些注解贯穿起来,一起进行讲解:
public class JunitTest {
private int count = 10;
public JunitTest() {
System.out.println("构造函数运行");
}
@BeforeClass
public static void beforeClass(){
System.out.println("BeforeClass...");
}
@AfterClass
public static void afterClass(){
System.out.println("AfterClass...");
}
@Before
public void setUp() throws Exception {
System.out.println("Before Method run...");
}
@After
public void tearDown() throws Exception {
System.out.println("After Method run...");
}
@Test
public void test1() throws Exception {
count++;
System.out.println("Test1 run,count=" + count);
}
@Test(expected = RuntimeException.class)
public void test2() throws Exception {
count++;
System.out.println("Test2 run, count=" + count);
throw new RuntimeException("Exception");
}
@Test(timeout = 500)
public void test3() throws Exception {
count++;
System.out.println("Test3 run, count=" + count);
Thread.sleep(300);
}
@Ignore
public void test4() throws Exception{
count++;
System.out.println("Test4 run, count=" + count);
}
}
程序的运行结果如下:
BeforeClass...
构造函数运行
Before Method run...
Test1 run,count=11