【问题标题】:How to use Testcontainers and Inject servcies in Quarkus?如何在 Quarkus 中使用 Testcontainers 和 Inject 服务?
【发布时间】:2022-09-23 04:58:01
【问题描述】:

我尝试迁移我的集成测试类以使用@Testcontainers。

原来的测试课就像

@QuarkusTest
class GameResourceTest {

    @Inject
    TeamService teamService;

    @Test
    void shouldLeadTheRankLadder() {
     teamService.doCrazyStuff();  // PASS

改写后是这样的

@Testcontainers
class GameResourceTest {

    @Container
    private MariaDBContainer mariaDBContainer = new MariaDBContainer(\"mariadb:10.5.16\").withDatabaseName(\"test\").withUsername(\"test\").withPassword(\"test\");
    
    @Inject
    TeamService teamService;

    @Test
    void test() {
     assertTrue(mariaDBContainer.isRunning()); // PASS
    }

    @Test
    void shouldLeadTheRankLadder() {
     teamService <-----------------------IS NULL HERE

因此,在删除 @QuarkusTest 注释后,我的服务的依赖注入不再起作用。

如何在这里使用测试容器和依赖注入?

    标签: quarkus testcontainers


    【解决方案1】:

    将 Testcontainers 与 Quarkus 集成的正确方法是使用通过 QuarkusTestResourceLifecycleManager 启动容器。

    请参阅 this 示例类,它正是这样做的。

    我还应该提到依赖注入@QuarkusTest 测试中工作

    【讨论】:

    • 这如何解决我的 DO 不再工作的问题?
    • 因为 DI 将在 @QuarkusTest 中工作
    【解决方案2】:

    将 Quarkus 与 Testcontainers 一起使用的最佳方式是使用 QuarkusTestResourceLifecycleManager guide

    Quarkus Kotlin 示例:

    
    class DatabaseTestLifeCycleManager : QuarkusTestResourceLifecycleManager {
        private val postgresDockerImage = DockerImageName.parse("postgres:latest")
    
        override fun start(): MutableMap<String, String>? {
            val container = startPostgresContainer()
    
            return mutableMapOf(
                "quarkus.datasource.username" to container.username,
                "quarkus.datasource.password" to container.password,
                "quarkus.datasource.jdbc.url" to container.jdbcUrl
            )
        }
    
        private fun startPostgresContainer(): PostgreSQLContainer<out PostgreSQLContainer<*>> {
            val container = PostgreSQLContainer(postgresDockerImage)
                .withDatabaseName("dataBaseName")
                .withUsername("username")
                .withPassword("password")
            container.start()
            return container
        }
    
        override fun stop() {
            // close container
        }
    }
    

    在您的测试中,使用 @QuarkusTestResource 对其进行注释

    例子:

    @QuarkusTest
    @QuarkusTestResource(DatabaseTestLifeCycleManager::class, restrictToAnnotatedClass = true)
    class MyTest {
    
        @Inject
        lateinit var dependency: InjectableDependency
    
        @InjectMock
        lateinit var mockedDependency: AnotherInjectableDependency
    }
    

    【讨论】:

      猜你喜欢
      • 2020-12-04
      • 1970-01-01
      • 2020-08-10
      • 1970-01-01
      • 2020-12-19
      • 1970-01-01
      • 2021-08-06
      • 1970-01-01
      • 2022-01-23
      相关资源
      最近更新 更多