SPRING BOOT單元測試中,因為測試時可能對應的服務器地址不同于SIT等別的環境,通常會將這些地址放于application-sit.yaml中。
在單元測試的代碼中用這個標簽指定用哪個profile,如
@ActiveProfiles({"embedded-mongodb","test"})
但這樣做法,由于@ActiveProfiles這個標簽是final的,如果要測試別的profile,只能復制另一份單元測試代碼,再改此標簽。
比較靈活的做法是用default profile,default profile是如果沒指定任何profile,則會默認用這個。在application-default.yaml中再指定需激活的profile。
spring:
profiles:
active: test,embedded-mongodb
如果要測試別的profile,可以指定環境變量的方式覆蓋:
-Dspring.profiles.active=error,embedded-mongodb
為了安全起見,將application-default.yaml放在測試目錄中:src\test\resources。
Setting default Spring profile for tests with override option
https://blog.inspeerity.com/spring/setting-default-spring-profile-for-tests-with-override-option/