Junit (三) 注解的使用

本文介绍了JUnit框架中的常用注解,包括@Test、@Ignore、@Before等,并通过示例代码展示了这些注解的具体应用方式。

  今天介绍一下Junit 中注解的使用。Junit中的注解有很多,这里不一一介绍。常用的注解如下:

  1. @Test: 测试方法

  2. @Ignore: 被忽略的测试方法

  3. @Before: 每一个测试方法之前运行

  4. @After: 每一个测试方法之后运行

  5. @BeforeClass: 所有测试开始之前运行

  6. @AfterClass: 所有测试结束之后运行


以下是示例代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package com.junit.test;
 
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
 
import static org.junit.Assert.*;
import static org.hamcrest.Matchers.*;
 
import com.junit.junit4.T;
 
public class TTest {
     
    /**
     * 所有测试之前运行
     */
    @BeforeClass
    public static void  beforeClass(){
        System.out.println("This is a beforeClass method");
    }
     
    /**
     * 所有测试之后运行
     */
    @AfterClass
    public static void  afterClass(){
        System.out.println("This is a afterClass method");
    }
     
    /**
     * 每一个测试方法之前运行
     */
    @Before
    public void before(){
        System.out.println("this is a before method");
    }
     
    /**
     * 每一个测试方法之后运行
     */
    @After
    public void after(){
        System.out.println("this is a before method");
    }
 
    @Test
    public void testAdd() {
        //fail("Not yet implemented");
        int sum = new T().add(53);
         
        //判断程序运行结果是否与期望值一致
        assertEquals(8, sum);
    }
     
    @Test
    public void testAdd2() {
        //fail("Not yet implemented");
        int sum = new T().add(53);
         
        //判断程序运行结果是否与期望值一致
        assertEquals(8, sum);
        assertTrue("This is TestString",8>sum);
        //assertThat("assertThat",8 > sum);
    }
     
    @Test
    public void testMinus(){
        int result = new T().minus(82);
        assertThat(result,is(4));
    }
 
 
}

上述代码的运行结果如下:

1
2
3
4
5
6
7
8
This is a beforeClass method
this is a before method
this is a before method
this is a before method
this is a before method
this is a before method
this is a before method
This is a afterClass method

大家可以参考上面的代码和运行结果理解其中的意思。



本文转自 乌英达姆 51CTO博客,原文链接:http://blog.51cto.com/7156680/1979477

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值