@Before, @BeforeClass, @After, @AfterClass区别

本文介绍了JUnit中的@BeforeClass、@Before、@AfterClass及@After等注解的使用方法及注意事项,包括它们在测试类中如何执行以及执行次数等方面的内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

@Before, @After注解过的方法将在测试方法之前/之后执行。

当然类里面可以有多个注解过@Before和@After的方法。如

注意的是如果多个的话,执行顺序是未知的


package test;

import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

public class TestDefaultController {
private Controller controller;

@BeforeClass
public static void sinstantiate() {
System.out.println();
}

@BeforeClass
public static void sinstantiate1() {
System.out.println();
}

@Before
public void instantiate() {
controller = new DefaultController();
}

@Before
public void instantiate1() {
controller = new DefaultController();
}

@Test
public void testMethod() {
throw new RuntimeException("implement me");
}

@Test
public void testMethod1() {
throw new RuntimeException("implement me");
}
}

 


@BeforeClass  @AfterClass注解是junit提供的另外的两个注解。

设置在public 静态方法之上,表示在class加载之前执行。这样设置的方法只会执行一次。而@Before @After则会再每次test之前/之后执行。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值