junit是一个开源的Java语言的单元测试框架。目前junit主要有版本junit3,junit4和junit5。因在junit3中,是通过对测试类和测试方法的命名来确定是否是测试,且所有的测试类必须继承junit的测试基类TestCase,所以本文不再讨论junit3,只讨论使用比较多的junit4和junit5。
(1)@Test
使用@Test注解测试方法。但测试方法必须是 public void。方法名一般为testXXX,通常需要见名知起义。
(2)@BeforeClass和@AfterClass
注意,@BeforeClass和@AfterClass注解的方法必须是static方法。
(3)@Before和@After
(4)@Parameters
使用@Parameters注解数据源方法。
(5)@Ignore
使用@Ignore忽略测试方法,被该注解标识的测试方法会被忽略不执行。
本文代码详情请见:https://github.com/X-NaN/studyjunit
- public class JunitAnnotationTest {
-
- /**
- * @BeforeClass 注解的必须是static方法
- */
- @BeforeClass
- public static void beforeClass() {
- System.out.println("@BeforeClass: 在该测试类内所有方法之前执行,只执行一次");
- }
-
- @Before
- public void beforeMethod() {
- System.out.println("@Before: 在每个测试方法之前执行一次");
- }
-
- @Test
- public void testCaseA() {
- System.out.println("@Test: 标识测试方法testCaseA");
- }
-
- @Test
- public void testCaseB() {
- System.out.println("@Test: 标识测试方法testCaseB");
- }
-
- /**
- * 异常测试
- */
- @Test(expected = ArithmeticException.class)
- public void testCaseException() {
- System.out.println("@Test: 标识测试方法testCaseException, 异常测试");
- System.out.println(1 / 0);
- }
-
- /**
- * 超时测试
- *
- * @throws InterruptedException
- */
- @Test(timeout = 1000)
- public void testCaseTimeOut() throws InterruptedException {
- System.out.println("@Test: 标识测试方法testCaseTimeOut,超时");
-
- // 若方法的超时时间超过timeout,则用例失败,否则成功
- Thread.sleep(1000);
- }
-
- @Ignore
- public void testCaseC() {
- System.out.println("@Ignore: 标识测试方法被忽略,不执行");
- }
-
- @After
- public void afterMethod() {
- System.out