[英]Running SpringBootTest Context Without Testcontainers Launch
我有 2 個家長測試課程:
@SpringBootTest(properties = {
"spring.datasource.url=jdbc:tc:mysql:8.0.25:///my_test_db?TC_INITSCRIPT=db/init_mysql.sql",
"spring.datasource.driver-class-name=org.testcontainers.jdbc.ContainerDatabaseDriver"
})
@TestConstructor(autowireMode = TestConstructor.AutowireMode.ALL)
public abstract class UserApplicationIntegrationTest {
}
和
@SpringBootTest
@TestConstructor(autowireMode = TestConstructor.AutowireMode.ALL)
public abstract class UserApplicationTest {
}
這個想法是讓各種測試類擴展這些類。 需要模擬 MySQL DB 的數據庫將擴展 UserApplicationIntegrationTest。 不需要數據庫連接但需要 Spring 上下文的那些將擴展 UserApplicationTest。
在沒有 UserApplicationIntegrationTest 的情況下,所有擴展 UserApplicationTest 的測試類都運行良好,包括使用 Mockito 框架。 不幸的是,當我介紹 UserApplicationIntegrationTest 及其子測試(與 dockerised db 實例完美配合)時,這些測試開始失敗,因為它們突然需要數據源。
Caused by: org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Failed to determine a suitable driver class
如果我嘗試在應用程序屬性或父 class 的注釋中排除數據源自動配置,則由於 Spring 上下文存在問題,testcontainers 測試(那些擴展 UserApplicationIntegrationTest)開始失敗,並且無法在這些測試中再自動裝配 bean .
在我知道之前,我已經陷入了一個嘗試混亂的排除/添加的兔子洞,這是我以前在以前的項目中遇到過的,它只會導致進一步的問題。
本質上,我希望在我的項目中共存 3 種類型的測試:
我想避免為所有 Spring 上下文測試啟動測試容器的最初原因(這將“工作”得很好,並且只包括構建過程中的 1 docker 延遲)是因為它讓我不得不等待 Z825B6053C41A2130AFD6FC3B158BDA4E6Z 延遲連接到 Z825B6053C41A2130AFD6FC3B158BDA4E6Z 讓我很惱火。每次我在開發過程中在本地運行單獨的 Spring 上下文測試時,都會對實例進行 dockerised。
有沒有一種簡潔的方法來實現這一目標,或者有一種更好的方法來滿足需求?
提前致謝。
希望我理解正確,我所做的是實現一個抽象的 TestContainer 測試 class:
package de.dwosch.it;
@ActiveProfiles("test")
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@ContextConfiguration(initializers = AbstractPostgreSQLTestContainerIT.Initializer.class)
@Testcontainers
public abstract class AbstractPostgreSQLTestContainerIT {
private static final String POSTGRES_VERSION = "postgres:11.1";
public static PostgreSQLContainer database;
static {
database = new PostgreSQLContainer(POSTGRES_VERSION);
database.start();
}
static class Initializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
@Override
public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
TestPropertySourceUtils.addInlinedPropertiesToEnvironment(
configurableApplicationContext,
"spring.datasource.url=" + database.getJdbcUrl(),
"spring.datasource.username=" + database.getUsername(),
"spring.datasource.password=" + database.getPassword()
);
}
}
}
然后我只是通過這個抽象的 class 擴展我的測試類,它將啟動一個測試容器和整個 spring 上下文以便更好地分離
class MyAwesomeControllerIT extends AbstractPostgreSQLTestContainerIT { }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.