@Before和@BeforeClass都是JUnit测试框架中的注解,它们在测试执行过程中的作用不同:
来说明@Before和@BeforeClass的区别:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
public class MyTest { @BeforeClass public static void runOnceBeforeClass() { System.out.println("This is run once before any test methods in this class."); }
@Before public void runBeforeEveryTest() { System.out.println("This is run before each test method in this class."); }
@Test public void testMethod1() { System.out.println("Running test method 1."); }
@Test public void testMethod2() { System.out.println("Running test method 2."); } } |
输出会是:
This is run once before any test methods in this class.
This is run before each test method in this class.
Running test method 1.
This is run before each test method in this class.
Running test method 2.
可以看到,runOnceBeforeClass()方法只运行了一次,而runBeforeEveryTest()方法在每个测试方法之前都运行了。