java - 如何在内存中嵌入 MariaDB4j 以替换 JUnit 测试中默认的 Spring DataSource?

标签 java spring junit spring-data-jpa spring-test

我正在为使用多个数据 Jpa 存储库的 Service 编写测试。问题在于,某些存储库使用大量带有 MySQL 特定函数的 native 查询,例如 str_to_date()。因此,当我尝试使用 H2 测试服务的方法时,我收到一条错误消息,指出 H2 无法识别函数。我尝试过在MySQL模式下使用H2,但得到了同样的错误。

here mariaDB4j 被提议作为一种解决方法。我已将依赖项添加到 Maven

<dependency>
    <groupId>ch.vorburger.mariaDB4j</groupId>
    <artifactId>mariaDB4j</artifactId>
    <version>2.3.0</version>
    <scope>test</scope>
</dependency>

但是出现IllegalStateException:无法用嵌入式数据库替换 DataSource 进行测试。如果您想要一个嵌入式数据库,请将受支持的数据库放在类路径上或调整 @AutoConfigureTestDatabase 的替换属性

我的测试文件如下所示:

@RunWith(SpringRunner.class)
@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.ANY)
public class TestPay {

    @TestConfiguration
    static class PaymentServiceTestContextConfiguration {
        @Bean
        public PaymentService paymentService(){
            return new PaymentService();
        }
    }

    @Autowired
    private PaymentService paymentService;
    @Autowired
    private TarifRepository firstRepository;
    @Autowired
    private BuildingRepository secondRepository;
    @Autowired
    private ApartmentRepository thirdRepository;

    /* Test cases here*/
}

该项目是使用注释驱动的 Spring Boot 构建的。

最佳答案

我构建了以下类,在每个需要数据库访问 mariadb 的集成测试中重用该类。它可能可以改进(我很乐意提供建议),但到目前为止它有效:

@RunWith(SpringRunner.class)
@SpringBootTest
@TestPropertySource(locations="classpath:application-junit.properties")
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) //otherwise mariadb is not cleaned up between tests
public abstract class MyIntegrationTest {

    private static MariaDB4jSpringService DB;

    @BeforeClass
    public static void init() throws ManagedProcessException {
        DB = new MariaDB4jSpringService();
        DB.setDefaultPort(1234);
        DB.start();
        DB.getDB().createDB("yourtables");
        DB.getDB().source("schema.sql"); // init scripts from /src/test/resources/schema.sql
    }

    @AfterClass
    public static void cleanup() {
        if (DB != null) DB.stop();
    }
}

应用程序-junit.properties:

spring.datasource.url=jdbc:mariadb://localhost:1234/yourtables
spring.datasource.username=root
spring.datasource.password=

关于java - 如何在内存中嵌入 MariaDB4j 以替换 JUnit 测试中默认的 Spring DataSource?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54556185/

相关文章:

java - 如何检查我是否在 hibernate 中使用 c3p0?

java - Drools Flow 能否扩展到每天执行数十万个流程实例?

java - Spring SOAP Web 服务 - 显示来自数据库/路径的图像

java - 模拟一个返回 Stream 并被多次调用的方法

java - gradle:如何从根项目运行子项目的 JUnit 测试?

java - 使用 JUnit 测试返回多个值的 API

Java 引用同一目录中的类

java - 如何将Javafx中的日期选择器设置和更新为最长2个月?

java - 在 CircleCi 中从 Spring Boot 访问 PostgreSQL 9.6

database - Spring Framework 中的默认隔离级别