Junit单元测试

Junit是干什么的我在这里就不讲解了。直接开始正题。

常用的注解

Junit中的注解很多,我们首先来看一下最常用的一些注解

  • @Test:把一个方法标记未测试方法
    • excepted:用来测试异常的,方法抛出该异常说明测试成功
    • timeout:用来测试性能的,在规定的时间内完成,说明成功。注意单位是毫秒
  • @Before:每个测试方法执行前自动调用一次
  • @After:每个测试方法执行完自动调用一次
  • @BeforeClass:在类被加载到内存中后执行,这意味着方法需要时static的,并且在构造函数之前执行
  • @AfterClass:在类被销毁之前执行,所以需要时static的
  • @Ignore:暂不执行该测试方法

下面我们将使用一个简单的例子,将这些注解贯穿起来,一起进行讲解:

public class JunitTest {
   
    private int count = 10;

    public JunitTest() {
        System.out.println("构造函数运行");
    }

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

    @AfterClass
    public static void afterClass(){
        System.out.println("AfterClass...");
    }

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

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

    @Test
    public void test1() throws Exception {
        count++;
        System.out.println("Test1 run,count=" + count);
    }

    @Test(expected = RuntimeException.class)
    public void test2() throws Exception {
        count++;
        System.out.println("Test2 run, count=" + count);
        throw new RuntimeException("Exception");
    }

    @Test(timeout = 500)
    public void test3() throws Exception {
        count++;
        System.out.println("Test3 run, count=" + count);
        Thread.sleep(300);
    }

    @Ignore
    public void test4() throws Exception{
        count++;
        System.out.println("Test4 run, count=" + count);
    }
}

程序的运行结果如下:

BeforeClass...
构造函数运行
Before Method run...
Test1 run,count=11
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值