当使用JUnit进行单元测试时,有两种类似的方法,setUp()setUpBeforeClass().这两种方法有什么不同?还有,tearDown()tearDownAfterClass()有什么不同呢?

以下是签名:

@BeforeClass
public static void setUpBeforeClass() throws Exception {
}

@AfterClass
public static void tearDownAfterClass() throws Exception {
}

@Before
public void setUp() throws Exception {
}

@After
public void tearDown() throws Exception {
}

推荐答案

在测试运行期间,@BeforeClass@AfterClass个带注释的方法将只运行一次——在整个测试的开始和结束时,在运行任何其他方法之前.事实上,它们甚至在构建测试类之前就已经运行了,这就是为什么它们必须被声明为static.

@Before@After方法将在每个测试用例之前和之后运行,因此在测试运行期间可能会运行多次.

假设你的类中有三个测试,方法调用的顺序是:

setUpBeforeClass()

  (Test class first instance constructed and the following methods called on it)
    setUp()
    test1()
    tearDown()

  (Test class second instance constructed and the following methods called on it)
    setUp()
    test2()
    tearDown()

  (Test class third instance constructed and the following methods called on it)
    setUp()
    test3()
    tearDown()

tearDownAfterClass()

Java相关问答推荐

'在使用apache poi生成Excel数据透视表时,行标签显示为第一列标题,并显示分类汇总

如何将一些命令写入Chrome控制台,然后使用Java将输出存储在selenium中

通过推送通知向自己发送Matrix消息

Javascript更新alert 可扩展内容样式与CSS—按钮更多/更少

Spring boot:Bean和动态扩展器

尽管类型擦除,instanceof与泛型在Java中如何工作?

我不能再在Android Studio Hedgehog上用Java语言创建新项目了吗?

使用用户引入的参数生成人员数组

来自外部模块的方面(对于Java+Gradle项目)不起作用

如何在列表(链表)中插入一个新 node (作为prelast)

如何以编程方式保存workBench.xmi?

IntelliJ IDEA依赖项工具窗口丢失

在使用具有不同成本的谓词调用allMatch之前对Java流进行排序会带来什么好处吗?

如何在SWT菜单项文本中保留@字符

如何使用Java对随机生成的字母数字优惠券代码进行过期设置

我们可以在方法中声明接口吗?

如何使用jOOQ在PostgreSQL中从枚举类型生成Java枚举

如何使用我的RLE程序解决此问题

原始和参数化之间的差异调用orElseGet时可选(供应商)

始终使用Spring Boot连接mongodb上的测试数据库