載入不同的 yaml 或屬性檔案或覆蓋某些屬性
當我們使用 @SpringApplicationConfiguration
時,它將使用 application.yml
[properties]的配置,在某些情況下這是不合適的。因此,要覆蓋屬性,我們可以使用 @TestPropertySource
註釋。
@TestPropertySource(
properties = {
"spring.jpa.hibernate.ddl-auto=create-drop",
"liquibase.enabled=false"
}
)
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(Application.class)
public class ApplicationTest{
// ...
}
我們可以使用 @TestPropertySource
的屬性屬性來覆蓋我們想要的特定屬性。在上面的例子中,我們壓倒一切的屬性 spring.jpa.hibernate.ddl-auto
到 create-drop
。而 liquibase.enabled
到 false
。
載入不同的 yml 檔案
如果要完全載入不同的 yml 檔案進行測試,可以在 @TestPropertySource
上使用 locations 屬性。
@TestPropertySource(locations="classpath:test.yml")
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(Application.class)
public class ApplicationTest{
// ...
}
或者選擇
選項 1:
你也可以載入不同 YML 檔案我放置一個 YML 檔案上 test > resource
目錄
選項 2:
使用 @ActiveProfiles
註釋
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@ActiveProfiles("somename")
public class MyIntTest{
}
你可以看到我們正在使用 @ActiveProfiles
註釋,我們將 somename 作為值傳遞。
建立一個名為 application-somename.yml
的檔案,測試將載入此檔案。