JUnit运行流程及常用注解

本文详细介绍了JUnit的运行流程,@BeforeClass和@AfterClass在所有测试方法前仅执行一次,@Before和@After则在每个方法前后各执行一次。@BeforeClass适合加载配置文件,@AfterClass用于资源清理。此外,还讲解了@Test注解的使用,包括预期异常和超时设置,以及如何使用@Ignore忽略测试方法。

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

一、运行流程

在test文件夹下新建一个JUnitTest测试类,勾选自动提供的四个method stubs。

package com.junit;

import static org.junit.Assert.*;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

public class JunitTest {
    @BeforeClass
    public static void setUpBeforeClass() throws Exception {
        System.out.println("BeforeClass");
    }

    @AfterClass
    public static void tearDownAfterClass() throws Exception {
        System.out.println("AfterClass");
    }

    @Before
    public void setUp() throws Exception {
        System.out.println("Before");
    }

    @After
    public void tearDown() throws Exception {
        System.out.println("After");
    }

    @Test
    public void test1() {
        System.out.println("test1");
    }

    @Test
    public void test2(){
        System.out.println("test2");
    }
}

运行程序可以发现,@BeforeClass和@AfterClass在所有方法被调用前执行一次,而@Before和@After会在每个测试方法前后各执行一次。

@BeforeClass是静态的,当测试类加载后接着就会执行它,内存中只有一份实例,比较适合加载配置文件;
@AfterClass所修饰的方法用来对资源的清理,如关闭对数据库的连接。

二、常用注解

@Test:将每个普通方法修饰为测试方法
1、expected = XXX.class

@Test(expected = ArithmeticException.class)
public void testDivide() {
    assertEquals(4,new Number().divide(8, 0));
}

2、timeout

@Test(timeout = 2000)
public void testReadFile(){
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

@Ignore:所修饰的测试方法会被测试器忽略

@Ignore
@Test(timeout = 1000)
public void testWhile(){
    while(true){
        System.out.println("hello world");
    }
}

@BeforeClass:在所有方法运行前被执行,static修饰
@AfterClass:在所有方法运行结束后被执行,static修饰
@Before:在每个测试方法运行前执行一次
@After:在每个测试方法运行后执行一次

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值