关于 junit4 中的 @Before @After @BeforeClass @AfterClass @Ignore 和 timeout expected 的使用

时间:2021-05-29 05:04:45
学习了junit4 测试框架后,领略了这个优秀框架的短小精悍,并对@Before @After @BeforeClass @AfterClass  @Ignore 和 timeout  expected

进行了代码实验,如下所示!

/**
*
*/
package com.bdr.irts.test;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;

/**
* Junit4 实验
* @author pengshuangbao
* @date 2014-3-17
*/
public class MyJunit4Test
{
/**
* 每个测试方法之前调用,每个方法都会调用
*/
@Before
public void before()
{
System.out.println("method before");
}

/**
* 每个测试方法之后调用,每个方法都会调用
*/
@After
public void after()
{
System.out.println("method before");
}

/**
* 每次执行之前调用 ,并且只能调用一次,必须为静态空返回值的方法
*/
@BeforeClass
public static void beforeClass()
{
System.out.println("###before class");
}

/**
* 每次执行之后调用 ,并且只能调用一次,必须为静态空返回值的方法
*/
@AfterClass
public static void afterClass()
{
System.out.println("###after class");
}

/**
* 普通测试方法
*/
@org.junit.Test
public void test()
{
System.out.println(" ******** my test");
}

/**
* 测试超时时间,如果超过了指定的时间就会测试失败
* @throws InterruptedException
*/
@Test(timeout = 1000)
public void testTime() throws InterruptedException
{
System.out.println(" ******** begin test");
Thread.sleep(5000);
System.out.println(" ******** end test");
}

/**
* 测试预期异常,就是如果方法中抛出了异常,可以指定忽略
*/
@Test(expected = ArithmeticException.class)
public void testException()
{
System.out.println(" ******** test excepton");
System.out.println(10 / 0);
}
/**
* 测试忽略方法
*/
@Ignore
@Test
public void testIgnore()
{
System.out.println(" ******** this test is abolished");
}
}