目錄
?加載測試專用的屬性
運行結(jié)果
使用外部bean對測試
運行結(jié)果
測速類啟動web環(huán)境
我們在測試類中?
運行結(jié)果?
?加載測試專用的屬性
點開@SpringBootTest源碼中查看
可以在之后加入臨時配置, 也可以使用命令行args參數(shù)設(shè)置。?設(shè)置的測試專用參數(shù)會覆蓋配置文件中的。
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);
}
}
運行結(jié)果
也可以使用命令行參數(shù)
args = {"--test.properties=4321"},
命令行參數(shù)的優(yōu)先級比配置文件的高,所以當兩者共存的時候,以命令行的為主
@SpringBootTest(args = {"--test.properties=4321"},properties = {"test.properties=1234"})
?這個測試類設(shè)置的屬性只對當前測試有效,影響小
使用外部bean對測試
package com.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration//說明當前為配置類
public class TestBean {
@Bean//創(chuàng)建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);
}
}
運行結(jié)果
測速類啟動web環(huán)境
在測試類中運行一般是不會啟動服務器的,如下圖。都是顯示運行成功或失敗的信息
?我們Ctrl+b點進@SpringBootTest源碼中查看,有一個關(guān)于web的
?默認值是MOCK,mock:默認提供一個模擬的web環(huán)境,不會啟動內(nèi)嵌的服務器
我們在測試類中?
?
?第一個是以你配置文件指定的端口啟動,如果沒有就默認以8080啟動
第二個mock:默認提供一個模擬的web環(huán)境,不會啟動內(nèi)嵌的服務器
第三個是不啟動服務器
第四個是隨機端口啟動
我們測試隨機端口啟動
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(){
}
}
運行結(jié)果?
運行了兩次看端口結(jié)果,都是隨機的?文章來源:http://www.zghlxwxcb.cn/news/detail-426021.html
文章來源地址http://www.zghlxwxcb.cn/news/detail-426021.html
到了這里,關(guān)于SpringBoot測試配置屬性與啟動web環(huán)境的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!