junit5常用注解

Junit5使用注解配置测试和扩展框架

@BeforeAll:表示在所有单元测试之前执行,只执行一次

@BeforeEach:表示在每个单元测试之前执行,假如测试类有n个测试方法,则被执行n次

@Test:表示方法是测试方法。但是与junit4的@Test不同,它的职责非常单一,不能声明任何属性,拓展的测试将会由Jupiter提供额外测试

@AfterEach:表示在每个单元测试之后执行,假如测试类有n个测试方法,则被执行n次

@AfterAll:表示在所有单元测试之后执行,只执行一次

示例:

复制代码
package com.testcase;

import org.junit.jupiter.api.*;


public class Junit5DemoTest {

    @BeforeAll
    public static void initAll(){
        System.out.println("init all test");
    }

    @BeforeEach
    public void init(){
        System.out.println("init a test");
    }

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

    @AfterEach
    public void tearDown(){
        System.out.println("tear down a test");
    }

    @AfterAll
    public static void tearDownAll(){
        System.out.println("tear down all test");
    }
}
复制代码

运行结果:

复制代码
init all test

init a test
fun
tear down a test

tear down all test

Process finished with exit code 0
复制代码

@RepeatedTest:表示方法额外执行的次数

复制代码
package com.testcase;

import org.junit.jupiter.api.*;


public class Junit5DemoTest {

    @BeforeAll
    public static void initAll(){
        System.out.println("init all test");
    }

    @BeforeEach
    public void init(){
        System.out.println("init a test");
    }

    @Test
    @RepeatedTest(1)
    void fun(){
        System.out.println("fun");
    }

    @AfterEach
    public void tearDown(){
        System.out.println("tear down a test");
    }


    @AfterAll
    public static void tearDownAll(){
        System.out.println("tear down all test");
    }
}
复制代码

运行结果:

@Disabled:表示测试类或测试方法不执行,类似于Junit4中的@Ignore

 @DisplayName:为测试类或测试方法设置展示名称

复制代码
package com.testcase;

import org.junit.jupiter.api.*;

@DisplayName("Junit5演示类")
public class Junit5DemoTest {

    @BeforeAll
    public static void initAll(){
        System.out.println("init all test");
    }

    @BeforeEach
    public void init(){
        System.out.println("init a test");
    }

    @DisplayName("fun测试方法")
    @Test
    void fun(){
        System.out.println("fun");
    }

    @Test
    @Disabled
    @DisplayName("fun1测试方法")
    void fun1(){
        System.out.println("fun1");
    }

    @AfterEach
    public void tearDown(){
        System.out.println("tear down a test");
    }


    @AfterAll
    public static void tearDownAll(){
        System.out.println("tear down all test");
    }
}
复制代码

运行结果:

@Tag:表示单元测试类别,类似于Junit4中的@Categories

表示为测试类或测试方法打一个标签。一般来说不能单独使用,需要配合其他的标签一起使用,具体详看Junit5套件执行

 

@ParameterizedTest:表示方法是参数化测试

具体详看jUnit5参数化

@Timeout:表示测试方法超过了指定时间将返回错误

@ExtendWith:为测试类或测试方法提供扩展类引用

@Nested:表示嵌套执行



posted @   未来可期_Durant  阅读(549)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示