本文主要是介绍Before和BeforeClass的区别及说明,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
《Before和BeforeClass的区别及说明》:本文主要介绍Before和BeforeClass的区别及说明,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教...
Before和BeforeClass的区别
@Before和@BeforeClass都是JUnit测试框架中的China编程注解,它们在测试执行过程中的作用不同:
@Before
:这个注解应用于一个方法上,这个方法会android在每一个测试方法执行之前被调用。这对于执行一些每个测试都需要的准备工作,如初始化变量,打开数据库连接等,非常有用。@BeforeClass
:这个注解应用于一个静态方法上,这个方法会在测试类中的所有测试方法执行之前被调用一次,而且只会被调用一次。这对于执行一些只需要在开始时执行一次的准备工作,如加载配置文件,设置环境变量等,非常有用。
一个简单的例子
来说明@Before和@BeforeClass的区别:
public class MyTest { @BeforeClass public static void runOnceBeforeClass() { Systemhttp://www.chinasem.cn.out.println("This is run ojavascriptnce 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()方法在TGRCfhT每个测试方法之前都运行了。
总结
这篇关于Before和BeforeClass的区别及说明的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!