如何使用测试中创建的bean来运行应用程序?

问题描述 投票:0回答:1

我正在为一个应用程序编写测试,其中在连接到 DB2 数据库时将数据源创建为 Bean。对于测试,我想使用内存中的 H2 数据库并调用 main 方法来运行应用程序。我已经在测试文件夹中使用 H2 数据库为数据源创建了一个 bean。然而,当我调用 main 方法时,控制始终转到原始应用程序,并且始终创建带有 DB2 数据库的 Bean。如何在应用程序中使用带有 H2 数据库的 bean?我在测试中编写的配置类从未被调用,因此从未创建带有 H2 数据库的 bean。

我在测试文件夹中有配置类,稍后会在测试文件中导入该类。

@TestConfiguration
@AutoConfiguration
public class H2Test {


@Primary
@Bean
@ConditionalOnMissingBean

public Datasource getH2bean() {
JdbcDataSource jdbcDataSource=new JdbcDataSource();
jdbcDataSource.setURL(<<Url to the H2 in-memory Database>>);
//further code
return jdbcDataSource;
}
}

我希望在运行完整的应用程序时使用上面的数据源 bean (

getH2bean
),因为我想调用应用程序的 main 方法。

我调用main方法的测试文件如下-

@SpringBootTest(classes={H2Test.class})
@ContectConfiguration(classes ={H2Test.class})
public class mainTest{


@Test
public void testMain() throws Exception{

A a=new A();
Assertions.assertDoesNotThrow(()-> a.main());
//call the main method of the application here
}
}

在这种情况下如何使用原始应用程序中的

getH2bean()

java spring-boot junit spring-jdbc spring-boot-test
1个回答
0
投票

您似乎没有为应用程序的开发和测试设置维护单独的配置。这基本上是维护专用的弹簧轮廓。

在 spring-boot 中,您可以创建一个

application.properties
包含实际数据库的数据库配置,比如说 postgre sql

spring.datasource.url= jdbc:postgresql://localhost:5432/testdb
spring.datasource.username= postgres
spring.datasource.password= dummypwd
# some more postgres specific properties

application-test.properties
包含您的 H2 数据库配置。

spring.datasource.url=jdbc:h2:file:./testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
 
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto= update
# some more H2 specific properties

然后在您的 Test 类中,您可以使用

@ActiveProfiles(value = "test")
注解来激活相应的配置文件,并加载与其关联的配置。

例如

@SpringBootTest(classes={H2Test.class})
@ContectConfiguration(classes ={H2Test.class})
@ActiveProfiles(value = "test")
public class mainTest{


@Test
public void testMain() throws Exception{

A a=new A();
Assertions.assertDoesNotThrow(()-> a.main());
//call the main method of the application here
}
}

请注意: 您可能需要将

mainTest
类中的第一行重构为
@SpringBootTest(classes = YourApplication.class) 
,其中
YourApplication.class
是 Spring-Boot 应用程序的主类

© www.soinside.com 2019 - 2024. All rights reserved.