溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

SpringBoot如何測試配置屬性與web啟動環境

發布時間:2022-10-24 09:29:10 來源:億速云 閱讀:163 作者:iii 欄目:開發技術

本篇內容介紹了“SpringBoot如何測試配置屬性與web啟動環境”的有關知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領大家學習一下如何處理這些情況吧!希望大家仔細閱讀,能夠學有所成!

加載測試專用的屬性

點開@SpringBootTest源碼中查看

SpringBoot如何測試配置屬性與web啟動環境

可以在之后加入臨時配置, 也可以使用命令行args參數設置。設置的測試專用參數會覆蓋配置文件中的。

package com;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest(args = {properties = {"test.properties=1234"})
public class TestProperties {
    @Value("${test.properties}")
    private String ps;
    @Test
    public void test(){
        System.out.println(ps);
    }
}

運行結果

SpringBoot如何測試配置屬性與web啟動環境

也可以使用命令行參數

args = {"--test.properties=4321"},

命令行參數的優先級比配置文件的高,所以當兩者共存的時候,以命令行的為主

@SpringBootTest(args = {"--test.properties=4321"},properties = {"test.properties=1234"})

SpringBoot如何測試配置屬性與web啟動環境

這個測試類設置的屬性只對當前測試有效,影響小

使用外部bean對測試

package com.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration//說明當前為配置類
public class TestBean {
    @Bean//創建bean
    public String mess(){
        return "this bean run ";
    }
}

在測試類下,使用@Import注解加載當前測試配置

package com.test;
import com.config.TestBean;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Import;
@SpringBootTest
@Import({TestBean.class})
public class TestBeanNow {
    @Autowired//注入bean對象
    public String mess;
    @Test
    public void test(){
        System.out.println(mess);
    }
}

運行結果

SpringBoot如何測試配置屬性與web啟動環境

測速類啟動web環境

在測試類中運行一般是不會啟動服務器的,如下圖。都是顯示運行成功或失敗的信息

SpringBoot如何測試配置屬性與web啟動環境

我們Ctrl+b點進@SpringBootTest源碼中查看,有一個關于web的

SpringBoot如何測試配置屬性與web啟動環境

默認值是MOCK,mock:默認提供一個模擬的web環境,不會啟動內嵌的服務器

我們在測試類中

SpringBoot如何測試配置屬性與web啟動環境

第一個是以你配置文件指定的端口啟動,如果沒有就默認以8080啟動

第二個mock:默認提供一個模擬的web環境,不會啟動內嵌的服務器

第三個是不啟動服務器

第四個是隨機端口啟動

我們測試隨機端口啟動

package com;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class WebTest {
    @Test
    public void test(){
    }
}

運行結果

運行了兩次看端口結果,都是隨機的

SpringBoot如何測試配置屬性與web啟動環境

“SpringBoot如何測試配置屬性與web啟動環境”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業相關的知識可以關注億速云網站,小編將為大家輸出更多高質量的實用文章!

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女