【发布时间】:2019-02-06 14:43:01
【问题描述】:
我正在为Service 编写测试,该测试使用多个 Jpa 数据存储库。问题是某些存储库使用大量具有MySQL 特定功能的本机查询,例如str_to_date()。因此,当我尝试使用H2 测试服务的方法时,我收到一条错误消息,提示 H2 无法识别功能。我曾尝试在 MySQL 模式下使用 H2,但得到了同样的错误。
heremariaDB4j 被提议作为一种解决方法。我已将依赖项添加到 Maven
<dependency>
<groupId>ch.vorburger.mariaDB4j</groupId>
<artifactId>mariaDB4j</artifactId>
<version>2.3.0</version>
<scope>test</scope>
</dependency>
但是得到IllegalStateException : Failed to replace DataSource with an embedded database for tests. If you want an embedded database please put a supported one on the classpath or tune the replace attribute of @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 构建的。
【问题讨论】:
-
对测试的简单评论,包括外部来源的 IMO 单元测试可能会变得脆弱。单元测试的目的是确保你的代码在做它应该做的事情。如果您可以通过模拟您的数据库而不是使用内存中的数据库来实现这一点,我会这样做。显然,这取决于您的团队和组织他们喜欢什么,这只是我的 2 美分。
-
恕我直言,在 JUnit 测试中测试尽可能多的集成是很有意义的,而不仅仅是严格意义上的单元测试。但实际上,这是一个“两个人 - 三个意见”的话题,我们应该在这里停止讨论...... ;-)
标签: java spring junit spring-data-jpa spring-test