java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Before和BeforeClass的区别

Before和BeforeClass的区别及说明

作者:我想要身体健康

这篇文章主要介绍了Before和BeforeClass的区别及说明,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教

Before和BeforeClass的区别

@Before和@BeforeClass都是JUnit测试框架中的注解,它们在测试执行过程中的作用不同:

一个简单的例子

来说明@Before和@BeforeClass的区别:

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()方法在每个测试方法之前都运行了。

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文