首页 > 其他分享 >junit复习1 @before class @after class

junit复习1 @before class @after class

时间:2022-12-02 10:34:00浏览次数:42  
标签:class System collection public void BeforeClass before junit out


先看代码

public class JunitTest1 {

private Collection collection;

@BeforeClass
public static void oneTimeSetUp() {
// one-time initialization code
System.out.println("@BeforeClass - oneTimeSetUp");
}

@AfterClass
public static void oneTimeTearDown() {
// one-time cleanup code
System.out.println("@AfterClass - oneTimeTearDown");
}

@Before
public void setUp() {
collection = new ArrayList();
System.out.println("@Before - setUp");
}

@After
public void tearDown() {
collection.clear();
System.out.println("@After - tearDown");
}

@Test
public void testEmptyCollection() {
assertTrue(collection.isEmpty());
System.out.println("@Test - testEmptyCollection");
}

@Test
public void testOneItemCollection() {
collection.add("itemA");
assertEquals(1, collection.size());
System.out.println("@Test - testOneItemCollection");
}
}



其中要注意的是 @BeforeClass和 @afterclass要在静态方法中使用,它们的含义为 :



1) 在一个类中只可以出现一次


2) @BeforeClass父类中标识了该Annotation的方法将会先于当前类中标识了该Annotation的方法执行。


@AfterClass 父类中标识了该Annotation的方法将会在当前类中标识了该Annotation的方法之后执行


3) 必须声明为public static


4) 所有标识为@AfterClass的方法都一定会被执行,即使在标识为@BeforeClass的方法抛出异常的的情况下也一样会


5) @BeforeClass 和 @AfterClass 对于那些比较“昂贵”的资源的分配或者释放来说是很有效的


标签:class,System,collection,public,void,BeforeClass,before,junit,out
From: https://blog.51cto.com/u_14230175/5905577

相关文章