今天介绍一下Junit 中注解的使用。Junit中的注解有很多,这里不一一介绍。常用的注解如下:
-
@Test: 测试方法
-
@Ignore: 被忽略的测试方法
-
@Before: 每一个测试方法之前运行
-
@After: 每一个测试方法之后运行
-
@BeforeClass: 所有测试开始之前运行
-
@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( 5 , 3 );
//判断程序运行结果是否与期望值一致
assertEquals( 8 , sum);
}
@Test
public void testAdd2() {
//fail("Not yet implemented");
int sum = new T().add( 5 , 3 );
//判断程序运行结果是否与期望值一致
assertEquals( 8 , sum);
assertTrue( "This is TestString" , 8 >sum);
//assertThat("assertThat",8 > sum);
}
@Test
public void testMinus(){
int result = new T().minus( 8 , 2 );
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