JUnit5常用注解的使用

2022-07-22,,

目录

注解(annotations)是junit的标志性技术,本文就来对它的20个注解,以及元注解和组合注解进行学习。

20个注解

在org.junit.jupiter.api包中定义了这些注解,它们分别是:

@test 测试方法,可以直接运行。

@parameterizedtest 参数化测试,比如:

@parameterizedtest
@valuesource(strings = { "racecar", "radar", "able was i ere i saw elba" })
void palindromes(string candidate) {
    asserttrue(stringutils.ispalindrome(candidate));
}

@repeatedtest 重复测试,比如:

@repeatedtest(10)
void repeatedtest() {
    // ...
}

@testfactory 测试工厂,专门生成测试方法,比如:

import org.junit.jupiter.api.dynamictest;

@testfactory
collection<dynamictest> dynamictestsfromcollection() {
    return arrays.aslist(
        dynamictest("1st dynamic test", () -> asserttrue(ispalindrome("madam"))),
        dynamictest("2nd dynamic test", () -> assertequals(4, calculator.multiply(2, 2)))
    );
}

@testtemplate 测试模板,比如:

final list<string> fruits = arrays.aslist("apple", "banana", "lemon");

@testtemplate
@extendwith(mytesttemplateinvocationcontextprovider.class)
void testtemplate(string fruit) {
    asserttrue(fruits.contains(fruit));
}

public class mytesttemplateinvocationcontextprovider
        implements testtemplateinvocationcontextprovider {

    @override
    public boolean supportstesttemplate(extensioncontext context) {
        return true;
    }

    @override
    public stream<testtemplateinvocationcontext> providetesttemplateinvocationcontexts(
            extensioncontext context) {

        return stream.of(invocationcontext("apple"), invocationcontext("banana"));
    }
}

@testtemplate必须注册一个testtemplateinvocationcontextprovider,它的用法跟@test类似。

@testmethodorder 指定测试顺序,比如:

import org.junit.jupiter.api.methodorderer.orderannotation;
import org.junit.jupiter.api.order;
import org.junit.jupiter.api.test;
import org.junit.jupiter.api.testmethodorder;

@testmethodorder(orderannotation.class)
class orderedtestsdemo {

    @test
    @order(1)
    void nullvalues() {
        // perform assertions against null values
    }

    @test
    @order(2)
    void emptyvalues() {
        // perform assertions against empty values
    }

    @test
    @order(3)
    void validvalues() {
        // perform assertions against valid values
    }

}

@testinstance 是否生成多个测试实例,默认junit每个测试方法生成一个实例,使用这个注解能让每个类只生成一个实例,比如:

@testinstance(lifecycle.per_class)
class testmethoddemo {

    @test
    void test1() {
    }

    @test
    void test2() {
    }

    @test
    void test3() {
    }

}

@displayname 自定义测试名字,会体现在测试报告中,比如:

import org.junit.jupiter.api.displayname;
import org.junit.jupiter.api.test;

@displayname("a special test case")
class displaynamedemo {

    @test
    @displayname("custom test name containing spaces")
    void testwithdisplaynamecontainingspaces() {
    }

    @test
    @displayname("╯°□°)╯")
    void testwithdisplaynamecontainingspecialcharacters() {
    }

    @test
    @displayname("😱")
    void testwithdisplaynamecontainingemoji() {
    }

}

@displaynamegeneration 测试名字统一处理,比如:

import org.junit.jupiter.api.displayname;
import org.junit.jupiter.api.displaynamegeneration;
import org.junit.jupiter.api.displaynamegenerator;
import org.junit.jupiter.api.indicativesentencesgeneration;
import org.junit.jupiter.api.nested;
import org.junit.jupiter.api.test;
import org.junit.jupiter.params.parameterizedtest;
import org.junit.jupiter.params.provider.valuesource;

class displaynamegeneratordemo {

    @nested
    @displaynamegeneration(displaynamegenerator.replaceunderscores.class)
    class a_year_is_not_supported {

        @test
        void if_it_is_zero() {
        }

        @displayname("a negative value for year is not supported by the leap year computation.")
        @parameterizedtest(name = "for example, year {0} is not supported.")
        @valuesource(ints = { -1, -4 })
        void if_it_is_negative(int year) {
        }

    }

    @nested
    @indicativesentencesgeneration(separator = " -> ", generator = displaynamegenerator.replaceunderscores.class)
    class a_year_is_a_leap_year {

        @test
        void if_it_is_divisible_by_4_but_not_by_100() {
        }

        @parameterizedtest(name = "year {0} is a leap year.")
        @valuesource(ints = { 2016, 2020, 2048 })
        void if_it_is_one_of_the_following_years(int year) {
        }

    }

}

@beforeeach 在每个@test, @repeatedtest, @parameterizedtest, or @testfactory之前执行。

@aftereach 在每个@test, @repeatedtest, @parameterizedtest, or @testfactory之后执行。

@beforeall 在所有的@test, @repeatedtest, @parameterizedtest, and @testfactory之前执行。

@afterall 在所有的@test, @repeatedtest, @parameterizedtest, and @testfactory之后执行。

@nested 嵌套测试,一个类套一个类,例子参考上面那个。

@tag 打标签,相当于分组,比如:

import org.junit.jupiter.api.tag;
import org.junit.jupiter.api.test;

@tag("fast")
@tag("model")
class taggingdemo {

    @test
    @tag("taxes")
    void testingtaxcalculation() {
    }

}

@disabled 禁用测试,比如:

import org.junit.jupiter.api.disabled;
import org.junit.jupiter.api.test;

@disabled("disabled until bug #99 has been fixed")
class disabledclassdemo {

    @test
    void testwillbeskipped() {
    }

}
@timeout 对于test, test factory, test template, or lifecycle method,如果超时了就认为失败了,比如:

class timeoutdemo {

    @beforeeach
    @timeout(5)
    void setup() {
        // fails if execution time exceeds 5 seconds
    }

    @test
    @timeout(value = 100, unit = timeunit.milliseconds)
    void failsifexecutiontimeexceeds100milliseconds() {
        // fails if execution time exceeds 100 milliseconds
    }

}

@extendwith 注册扩展,比如:

@extendwith(randomparametersextension.class)
@test
void test(@random int i) {
    // ...
}

junit5提供了标准的扩展机制来允许开发人员对junit5的功能进行增强。junit5提供了很多的标准扩展接口,第三方可以直接实现这些接口来提供自定义的行为。

@registerextension 通过字段注册扩展,比如:

class webserverdemo {

    @registerextension
    static webserverextension server = webserverextension.builder()
        .enablesecurity(false)
        .build();

    @test
    void getproductlist() {
        webclient webclient = new webclient();
        string serverurl = server.getserverurl();
        // use webclient to connect to web server using serverurl and verify response
        assertequals(200, webclient.get(serverurl + "/products").getresponsestatus());
    }

}

@tempdir 临时目录,比如:

@test
void writeitemstofile(@tempdir path tempdir) throws ioexception {
    path file = tempdir.resolve("test.txt");

    new listwriter(file).write("a", "b", "c");

    assertequals(singletonlist("a,b,c"), files.readalllines(file));
}

元注解和组合注解

junit jupiter支持元注解,能实现自定义注解,比如自定义@fast注解:

import java.lang.annotation.elementtype;
import java.lang.annotation.retention;
import java.lang.annotation.retentionpolicy;
import java.lang.annotation.target;

import org.junit.jupiter.api.tag;

@target({ elementtype.type, elementtype.method })
@retention(retentionpolicy.runtime)
@tag("fast")
public @interface fast {
}

使用:

@fast
@test
void myfasttest() {
    // ...
}

这个@fast注解也是组合注解,甚至可以更进一步和@test组合:

import java.lang.annotation.elementtype;
import java.lang.annotation.retention;
import java.lang.annotation.retentionpolicy;
import java.lang.annotation.target;

import org.junit.jupiter.api.tag;
import org.junit.jupiter.api.test;

@target(elementtype.method)
@retention(retentionpolicy.runtime)
@tag("fast")
@test
public @interface fasttest {
}

只用@fasttest就可以了:

@fasttest
void myfasttest() {
    // ...
}

小结

本文对junit20个主要的注解进行了介绍和示例演示,junit jupiter支持元注解,可以自定义注解,也可以把多个注解组合起来。

参考资料:

到此这篇关于junit5常用注解的使用的文章就介绍到这了,更多相关junit5注解内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

《JUnit5常用注解的使用.doc》

下载本文的Word格式文档,以方便收藏与打印。