我正在为使用多个数据 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/