簡體   English   中英

如何從 java 中的 static 字段中分離 System.getenv

[英]How to decouple System.getenv from static field in java

我有一個遺留代碼如下

@Service
public class CLConf {
    static final String CI_ENV = System.getenv("ENV").toUpperCase(); <-- NPE when doing junits
    // other config variables
}

當我們在應用程序中正常運行代碼時,這有效。 但我在創建使用 class CLConf的測試用例時遇到問題,如下所示。

@ExtendWith(SpringExtension.class)
@SpringBootTest
@ContextConfiguration(classes = CLConf.class) <<----------- ISSUE while loading bcz env is not set yet
public class CLServiceTest {
    //test cases
}

目前它因為.toUpperCase()而拋出 NPE

由於 CI_ENV 是直接從System.getenv設置的,在為 Junits 編寫 class 時,這個 class 是使用@ContextConfiguration加載的。 而且我不確定在哪里為測試用例設置環境變量,以便在加載env時不會CLConf

如何為測試用例配置/設置或如何解耦System.getenv以便在測試時提供自己的配置?

注意:class CLConf中有很多System.getenv,上面只是縮小了class。

您可以使用TestPropertySource注釋的locationsvalue屬性提供測試配置,直接在文件中定義測試屬性或選擇性地覆蓋文檔中所述的屬性:

@TestPropertySource 是一個類級別的注釋,用於配置屬性文件的位置()和內聯屬性(),以添加到環境的 PropertySources 集中,用於集成測試的 ApplicationContext。 測試屬性源的優先級高於從操作系統環境或 Java 系統屬性以及應用程序以聲明方式通過 @PropertySource 或以編程方式(例如,通過 ApplicationContextInitializer 或其他方式)添加的屬性源的優先級。 因此,測試屬性源可用於選擇性地覆蓋系統和應用程序屬性源中定義的屬性

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM