Junit中的@BeforeClass与@AfterClass

时间:2022-02-07 05:09:13
  • 首先,被声明为@BeforeClass@AfterClass的方法必须是public static void
  • 即使@BeforeClass中发生了异常,@AfterClass方法仍会执行,保证资源的释放(使用者操作) - 一个测试类是允许声明多个@BeforeClass@AfterClass,但是执行的顺序是不确定的
@BeforeClass public static void setUpBeforeClass1() throws Exception 
{
System.out.println("Before1");
}
@BeforeClass public static void setUpBeforeClass2() throws Exception
{
System.out.println("Before2");
}
@BeforeClass public static void setUpBeforeClass3() throws Exception
{
System.out.println("Before3");
}

执行结果1:
Before3
Before2
Before1
执行结果2:
Before1
Before3
Before2


  • 对于父类中的@BeforeClass会优先于子类中的@BeforeClass执行;同样@AfterClass会在子类@AfterClass之后执行,参考源码中的说明:

The @AfterClass methods declared in superclasses will be run after those of the current class.The @BeforeClass methods of superclasses will be run before those the current class.

对于多个测试类的公共初始化或资源释放部分,可移至抽象父类@BeforeClass@AfterClass中执行,比如在父类中完成spring的初始化,在个子测试类中get相应的bean。注意子类中与父类同名的函数会被覆盖哦

//抽象基类
public abstract class SuperUnit
{

@BeforeClass public static void setUpBeforeClass() throws Exception
{
System.out.println("super @BeforeClass");
}
@AfterClass public static void tearDownAfterClass() throws Exception
{
System.out.println("super @AfterClass");
}
}
//子测试类
public class TestUnit extends SuperUnit
{

@BeforeClass public static void setUpBeforeClass() throws Exception
{
System.out.println("@BeforeClass");
}
@AfterClass public static void tearDownAfterClass() throws Exception
{
System.out.println("@AfterClass");
}
@Test public void test()
{
System.out.println("test");
}
}

运行结果:
@BeforeClass
test
@AfterClass
并没有执行父类的@BeforeClass@AfterClass方法,因为是同名方法被重写了,TestUnit中区分函数名修改:

public class TestUnit extends SuperUnit
{

@BeforeClass public static void setUp() throws Exception
{
System.out.println("@BeforeClass");
}
@AfterClass public static void tearDown() throws Exception
{
System.out.println("@AfterClass");
}
@Test public void test() { System.out.println("test"); }}

执行结果:
super @BeforeClass
@BeforeClasstest
test
@AfterClass
super @AfterClass