Junit单元测试 | 注解和执行顺序

JUnit4注解基本介绍
JUnit4 中@AfterClass @BeforeClass @after @before的区别对比
junit之测试顺序

1、JUnit4基本注解

@Before

When writing tests, it is common to find that several tests need similar objects created before they can run. Annotating a public void method with @Before causes that method to be run before the Test method. The @Before methods of superclasses will be run before those of the current class. No other ordering is defined.

当编写测试方法时,经常会发现一些方法在执行前需要创建相同的对象。使用@Before注解一个public void 方法会使该方法在每个@Test注解方法被执行前执行(那么就可以在该方法中创建相同的对象)。

父类的@Before注解方法会在子类的@Before注解方法执行前执行。

@After

If you allocate external resources in a Before method you need to release them after the test runs.Annotating a public void method with @After causes that method to be run after the Test method. All @After methods are guaranteed to run even if a Before or Test method throws an exception. The @After methods declared in superclasses will be run after those of the current class.

使用@After注解一个public void方法会使该方法在每个@Test注解方法执行后被执行。

如果在@Before注解方法中分配了额外的资源,那么在测试执行完后,需要释放分配的资源,这个释放资源的操作可以在After中完成。

即使在@Before注解方法、@Test注解方法中抛出了异常,所有的@After注解方法依然会被执行。

父类中的@After注解方法会在子类@After注解方法执行后被执行。

@Test

The Test annotation tells JUnit that the public void method to which it is attached can be run as a test case. To run the method, JUnit first constructs a fresh instance of the class then invokes the annotated method. Any exceptions thrown by the test will be reported by JUnit as a failure. If no exceptions are thrown, the test is assumed to have succeeded.

The Test annotation supports two optional parameters.

The first, expected,declares that a test method should throw an exception. If it doesn't throw an exception or if it throws a different exception than the one declared, the test fails.

The second optional parameter, timeout, causes a test to fail if it takes longer than a specified amount of clock time (measured in milliseconds).

@Test注解的public void方法将会被当做测试用例,JUnit每次都会创建一个新的测试实例,然后调用@Test注解方法,任何异常的抛出都会认为测试失败。当以一个类为测试单元时,所有测试用例(测试方法)共属同一个测试实例(具有同一个环境);当以一个方法为测试单元时,JUnit每次都会创建一个新的测试实例。

@Test注解提供2个参数:
1,“expected”,定义测试方法应该抛出的异常,如果测试方法没有抛出异常或者抛出了一个不同的异常,测试失败;
2,“timeout”,如果测试运行时间长于该定义时间,测试失败(单位为毫秒)。

@BeforeClass

Sometimes several tests need to share computationally expensive setup (like logging into a database). While this can compromise the independence of tests, sometimes it is a necessary optimization.Annotating a public static void no-arg method with @BeforeClass causes it to be run once before any of the test methods in the class. The @BeforeClass methods of superclasses will be run before those the current class.

有些时候,一些测试需要共享代价高昂的步骤(如数据库登录),这会破坏测试独立性,通常是需要优化的。

使用@BeforeClass注解一个public static void 方法,并且该方法不带任何参数,会使该方法在所有测试方法被执行前执行一次,并且只执行一次。

父类的@BeforeClass注解方法会在子类的@BeforeClass注解方法执行前执行。

@AfterClass

If you allocate expensive external resources in a Before Class method you need to release them after all the tests in the class have run. Annotating a public static void method with @AfterClass causes that method to be run after all the tests in the class have been run. All @AfterClass methods are guaranteed to run even if a Before Class method throws an exception.The @AfterClass methods declared in superclasses will be run after those of thecurrent class.

如果在@BeforeClass注解方法中分配了代价高昂的额外的资源,那么在测试类中的所有测试方法执行完后,需要释放分配的资源。

使用@AfterClass注解一个public static void方法会使该方法在测试类中的所有测试方法执行完后被执行。

即使在@BeforeClass注解方法中抛出了异常,所有的@AfterClass注解方法依然会被执行。

父类中的@AfterClass注解方法会在子类@AfterClass注解方法执行后被执行。

@Ignore

Sometimes you want to temporarily disable a test or a group of tests. Methods annotated with Test that are also annotated with @Ignore will not be executed as tests. Also, you can annotate a class containing test methods with @Ignore and none of the containing tests will be executed. Native JUnit 4 test runners should report the number of ignored tests along with the number of tests that ran and the number of tests that failed.

对包含测试类的类或@Test注解方法使用@Ignore注解将使被注解的类或方法不会被当做测试执行;JUnit执行结果中会报告被忽略的测试数。

2、Junit测试顺序:@FixMethodOrder

Junit 4.11里增加了指定测试方法执行顺序的特性,测试类的执行顺序可通过对测试类添加注解 @FixMethodOrder(value)来指定,其中value 为执行顺序 ,下面是value值下对应的测试顺序行为:

  • ** MethodSorters.DEFAULT **(默认)
    默认顺序由方法名hashcode值来决定,如果hash值大小一致,则按名字的字典顺序确定。
    由于hashcode的生成和操作系统相关(以native修饰),所以对于不同操作系统,可能会出现不一样的执行顺序,在某一操作系统上,多次执行的顺序不变 。

  • ** MethodSorters.NAME_ASCENDING (推荐) **
    按方法名称的进行排序,由于是按字符的字典顺序,所以以这种方式指定执行顺序会始终保持一致;
    不过这种方式需要对测试方法有一定的命名规则,如 测试方法均以testNNN开头(NNN表示测试方法序列号 001-999) 。

  • ** MethodSorters.JVM **
    按JVM返回的方法名的顺序执行,此种方式下测试方法的执行顺序是不可预测的,即每次运行的顺序可能
    都不一样(JDK7里尤其如此)。

3、栗子

import org.junit.*;
import org.junit.runners.MethodSorters;

@FixMethodOrder(value = MethodSorters.DEFAULT)  // <<--- I will change here for testing ... 
public class MathTest {
    private static int flag = 0;

    @Test(timeout = 1000)
    public void testA(){
        System.out.println("here is testA");
        System.out.println("flag = " + flag);
        flag = 1;
        System.out.println("flag = " + flag);
    }

    @Test
    public void testB(){
        System.out.println("here is testB");
        System.out.println("flag = " + flag);
        flag = 2;
        System.out.println("flag = " + flag);
    }

    @Test
    public void testC(){
        System.out.println("here is testC");
        System.out.println("flag = " + flag);
        flag = 3;
        System.out.println("flag = " + flag);
    }

    @Before
    public void beforeEveryTest(){
        System.out.println("\n=== beforeEveryTest ===\n");
    }

    @After
    public void afterEveryTest(){
        System.out.println("\n=== afterEveryTest ===\n");
    }

    // must be static
    @BeforeClass
    public static void beforeClassTest(){
        System.out.println("\n===beforeClassTest===\n");
    }

    // must be static
    @AfterClass
    public static void afterClassTest(){
        System.out.println("\n===afterClassTest===\n");
    }

}

默认顺序

===beforeClassTest===


=== beforeEveryTest ===

here is testA
flag = 0
flag = 1

=== afterEveryTest ===


=== beforeEveryTest ===

here is testB
flag = 1
flag = 2

=== afterEveryTest ===


=== beforeEveryTest ===

here is testC
flag = 2
flag = 3

=== afterEveryTest ===


===afterClassTest===

字典顺序
同上

JVM顺序

===beforeClassTest===


=== beforeEveryTest ===

here is testB
flag = 0
flag = 2

=== afterEveryTest ===


=== beforeEveryTest ===

here is testA
flag = 2
flag = 1

=== afterEveryTest ===


=== beforeEveryTest ===

here is testC
flag = 1
flag = 3

=== afterEveryTest ===


===afterClassTest===
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,457评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,837评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,696评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,183评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,057评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,105评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,520评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,211评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,482评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,574评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,353评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,213评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,576评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,897评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,174评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,489评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,683评论 2 335

推荐阅读更多精彩内容