最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

JUnit5常用注解的使用

 更新時(shí)間:2021年07月02日 16:04:41   作者:自動(dòng)化代碼美學(xué)  
注解是JUnit的標(biāo)志性技術(shù),本文就來(lái)對(duì)它的20個(gè)注解,以及元注解和組合注解進(jìn)行學(xué)習(xí),感興趣的可以了解一下

注解(Annotations)是JUnit的標(biāo)志性技術(shù),本文就來(lái)對(duì)它的20個(gè)注解,以及元注解和組合注解進(jìn)行學(xué)習(xí)。

20個(gè)注解

在org.junit.jupiter.api包中定義了這些注解,它們分別是:

@Test 測(cè)試方法,可以直接運(yùn)行。

@ParameterizedTest 參數(shù)化測(cè)試,比如:

@ParameterizedTest
@ValueSource(strings = { "racecar", "radar", "able was I ere I saw elba" })
void palindromes(String candidate) {
    assertTrue(StringUtils.isPalindrome(candidate));
}

@RepeatedTest 重復(fù)測(cè)試,比如:

@RepeatedTest(10)
void repeatedTest() {
    // ...
}

@TestFactory 測(cè)試工廠,專門生成測(cè)試方法,比如:

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 測(cè)試模板,比如:

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必須注冊(cè)一個(gè)TestTemplateInvocationContextProvider,它的用法跟@Test類似。

@TestMethodOrder 指定測(cè)試順序,比如:

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 是否生成多個(gè)測(cè)試實(shí)例,默認(rèn)JUnit每個(gè)測(cè)試方法生成一個(gè)實(shí)例,使用這個(gè)注解能讓每個(gè)類只生成一個(gè)實(shí)例,比如:

@TestInstance(Lifecycle.PER_CLASS)
class TestMethodDemo {

    @Test
    void test1() {
    }

    @Test
    void test2() {
    }

    @Test
    void test3() {
    }

}

@DisplayName 自定義測(cè)試名字,會(huì)體現(xiàn)在測(cè)試報(bào)告中,比如:

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 測(cè)試名字統(tǒng)一處理,比如:

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 在每個(gè)@Test, @RepeatedTest, @ParameterizedTest, or @TestFactory之前執(zhí)行。

@AfterEach 在每個(gè)@Test, @RepeatedTest, @ParameterizedTest, or @TestFactory之后執(zhí)行。

@BeforeAll 在所有的@Test, @RepeatedTest, @ParameterizedTest, and @TestFactory之前執(zhí)行。

@AfterAll 在所有的@Test, @RepeatedTest, @ParameterizedTest, and @TestFactory之后執(zhí)行。

@Nested 嵌套測(cè)試,一個(gè)類套一個(gè)類,例子參考上面那個(gè)。

@Tag 打標(biāo)簽,相當(dāng)于分組,比如:

import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;

@Tag("fast")
@Tag("model")
class TaggingDemo {

    @Test
    @Tag("taxes")
    void testingTaxCalculation() {
    }

}

@Disabled 禁用測(cè)試,比如:

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 對(duì)于test, test factory, test template, or lifecycle method,如果超時(shí)了就認(rèn)為失敗了,比如:

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 注冊(cè)擴(kuò)展,比如:

@ExtendWith(RandomParametersExtension.class)
@Test
void test(@Random int i) {
    // ...
}

JUnit5提供了標(biāo)準(zhǔn)的擴(kuò)展機(jī)制來(lái)允許開(kāi)發(fā)人員對(duì)JUnit5的功能進(jìn)行增強(qiáng)。JUnit5提供了很多的標(biāo)準(zhǔn)擴(kuò)展接口,第三方可以直接實(shí)現(xiàn)這些接口來(lái)提供自定義的行為。

@RegisterExtension 通過(guò)字段注冊(cè)擴(kuò)展,比如:

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 臨時(shí)目錄,比如:

@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支持元注解,能實(shí)現(xiàn)自定義注解,比如自定義@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() {
    // ...
}

這個(gè)@Fast注解也是組合注解,甚至可以更進(jìn)一步和@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() {
    // ...
}

小結(jié)

本文對(duì)JUnit20個(gè)主要的注解進(jìn)行了介紹和示例演示,JUnit Jupiter支持元注解,可以自定義注解,也可以把多個(gè)注解組合起來(lái)。

參考資料:

https://junit.org/junit5/docs/current/user-guide/#writing-tests-annotations

https://vitzhou.gitbooks.io/junit5/content/junit/extension_model.html#概述

到此這篇關(guān)于JUnit5常用注解的使用的文章就介紹到這了,更多相關(guān)JUnit5注解內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 若依前后端打成一個(gè)JAR包部署的完整步驟

    若依前后端打成一個(gè)JAR包部署的完整步驟

    這篇文章主要介紹了如何將若依前后端分離項(xiàng)目打包成jar,不使用nginx轉(zhuǎn)發(fā),前端修改了路由模式和環(huán)境變量配置,后端增加了依賴、配置了Thymeleaf和訪問(wèn)路徑,需要的朋友可以參考下
    2025-01-01
  • WeakHashMap的垃圾回收原理詳解

    WeakHashMap的垃圾回收原理詳解

    這篇文章主要介紹了WeakHashMap的垃圾回收原理詳解,WeakHashMap 與 HashMap 的用法基本類似,與 HashMap 的區(qū)別在于,HashMap的key保留了對(duì)實(shí)際對(duì)象的強(qiáng)引用個(gè),這意味著只要該HashMap對(duì)象不被銷毀,該HashMap的所有key所引用的對(duì)象就不會(huì)被垃圾回收,需要的朋友可以參考下
    2023-09-09
  • Springboot集成Mybatis-plus、ClickHouse實(shí)現(xiàn)增加數(shù)據(jù)、查詢數(shù)據(jù)功能

    Springboot集成Mybatis-plus、ClickHouse實(shí)現(xiàn)增加數(shù)據(jù)、查詢數(shù)據(jù)功能

    本文給大家講解Springboot + mybatis-plus 集成ClickHouse,實(shí)現(xiàn)增加數(shù)據(jù)、查詢數(shù)據(jù)功能,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),感興趣的朋友跟隨小編一起看看吧
    2024-08-08
  • 詳解Java進(jìn)階知識(shí)注解

    詳解Java進(jìn)階知識(shí)注解

    這篇文章主要介紹了詳解Java進(jìn)階知識(shí)注解,從注解的定義、元注解、自定義注解、注解實(shí)例這幾個(gè)方面,讓同學(xué)們更加深入的了解注解
    2021-04-04
  • java8到j(luò)ava15的新功能簡(jiǎn)介

    java8到j(luò)ava15的新功能簡(jiǎn)介

    這篇文章主要介紹了java8到j(luò)ava15的新功能的相關(guān)資料,幫助大家更好的理解和學(xué)習(xí)Java,感興趣的朋友可以了解下
    2020-12-12
  • SpringBoot在生產(chǎn)快速禁用Swagger2的方法步驟

    SpringBoot在生產(chǎn)快速禁用Swagger2的方法步驟

    這篇文章主要介紹了SpringBoot在生產(chǎn)快速禁用Swagger2的方法步驟,使用注解關(guān)閉Swagger2,避免接口重復(fù)暴露,非常具有實(shí)用價(jià)值,需要的朋友可以參考下
    2018-12-12
  • SpringBoot整合DeepSeek實(shí)現(xiàn)AI對(duì)話功能

    SpringBoot整合DeepSeek實(shí)現(xiàn)AI對(duì)話功能

    本文介紹了如何在SpringBoot項(xiàng)目中整合DeepSeek API和本地私有化部署DeepSeekR1模型,通過(guò)SpringAI框架簡(jiǎn)化了人工智能模型的集成,感興趣的小伙伴跟著小編一起來(lái)看看吧
    2025-02-02
  • Springboot多數(shù)據(jù)源配置之整合dynamic-datasource方式

    Springboot多數(shù)據(jù)源配置之整合dynamic-datasource方式

    這篇文章主要介紹了Springboot多數(shù)據(jù)源配置之整合dynamic-datasource方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-03-03
  • 一文詳解SpringBoot使用Kafka如何保證消息不丟失

    一文詳解SpringBoot使用Kafka如何保證消息不丟失

    這篇文章主要為大家詳細(xì)介紹了SpringBoot使用Kafka如何保證消息不丟失的相關(guān)知識(shí),文中的示例代碼講解詳細(xì),有需要的小伙伴可以參考一下
    2025-01-01
  • Java中BufferedReader與Scanner讀入的區(qū)別詳解

    Java中BufferedReader與Scanner讀入的區(qū)別詳解

    這篇文章主要介紹了Java中BufferedReader與Scanner讀入的區(qū)別詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-10-10

最新評(píng)論

曲水县| 中江县| 澄江县| 夹江县| 石河子市| 二手房| 喀喇沁旗| 武山县| 仁怀市| 宜川县| 滨州市| 澄江县| 永德县| 叙永县| 江西省| 滦南县| 宜君县| 于田县| 墨脱县| 麟游县| 彭泽县| 北辰区| 尉犁县| 海阳市| 迁西县| 衡南县| 舟山市| 巧家县| 满城县| 南丰县| 砚山县| 赤峰市| 南充市| 山丹县| 沙河市| 慈利县| 喀喇沁旗| 合江县| 融水| 平南县| 淳化县|