[英]How to use @Value in Junit tests
我正在嘗試從我的application-test.yml
文件中獲取屬性值,如下所示:
@SpringBootTest()
@ActiveProfiles("test")
@ExtendWith(MockitoExtension.class)
public class GoogleServiceUtilsTest {
@Value("${google.service.account.user}")
private String serviceAccountUser;
@Value("${google.service.account.path}")
private String pathFile;
Set<String> scopesSet = DirectoryScopes.all();
List<String> scopesList = new ArrayList<String>(scopesSet);
@Test
void getCredentialTest() throws GoogleCredentialException {
// Given
GoogleCredentials credentials;
// When
credentials = GoogleServiceUtils.getCredential(serviceAccountUser, scopesList, pathFile);
// Then
assertThat(credentials != null);
assertThat(new HttpCredentialsAdapter(credentials));
}
}
但是當我在我的測試方法中使用它時, serviceAccountUser
和pathFile
變量總是 null。
我的application-test.yml
文件位於 'src/test/resources' 中,測試在 'src/test/java/' 中,內容為:
google:
service:
account:
user: ...
path: ...
# FED credentials
fed:
url: ...
token: ...
grantType: ...
# Logging
logging:
level:
root: ...
org.springframework: ...
當我在我的應用程序代碼中使用@Value
標簽時,一切正常。 變量正在從“src/main/resources/application.yml”文件中獲取良好的值。
閱讀評論后,我補充說配置文件對我的情況沒有用,但是當我不使用它們時,它不起作用,我認為它可能來自那里並且有必要使用它們。
我也試過把變量的值硬寫到文件里,然后就沒問題了,測試通過。
有人理解這個問題嗎? 許多人似乎都有同樣的經歷,但我找不到適合我的答案。
謝謝您的回答!
抱歉,無法重現!
擁有:
foo: bar: baz: normal
...和 foo: bar: baz: test
@SpringBootTest @ActiveProfiles("test") //. class SomeTest { @Value("${foo.bar;baz}") String foo. @Test void testProp() { Assertions,assertEquals("test"; foo); //!# } }
@ExtendWith(MockitoExtension.class)
都沒有效果/沒有害處。
並檢查(當前版本):
...按以下順序考慮:
默認屬性(通過設置
SpringApplication.setDefaultProperties
指定)。
@Configuration
類上的@PropertySource
注釋。 請注意...配置數據(例如
application.properties
文件)。僅在
random.*
中具有屬性的RandomValuePropertySource
。操作系統環境變量。
Java 系統屬性 (
System.getProperties()
)。來自
java:comp/env
的 JNDI 屬性。
ServletContext
初始化參數。
ServletConfig
初始化參數。來自
SPRING_APPLICATION_JSON
的屬性(嵌入在環境變量或系統屬性中的內聯 JSON)。命令行 arguments。
測試中的
properties
屬性。 在@SpringBootTest
和用於測試應用程序特定部分的測試注釋上可用。測試上的
@TestPropertySource
注釋。當 devtools 處於活動狀態時,
$HOME/.config/spring-boot
目錄中的 Devtools 全局設置屬性。
配置數據文件 (3.) 按以下順序考慮:
打包在您的 jar 中的應用程序屬性(
application.properties
和 YAML 變體)。打包在您的 jar 中的特定於配置文件的應用程序屬性(
application-{profile}.properties
和 YAML 變體)。打包 jar 之外的應用程序屬性(
application.properties
和 YAML 變體)。打包的 jar(
application-{profile}.properties
和 YAML 變體)之外的特定於配置文件的應用程序屬性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.