【问题标题】:How to write integration test for JPA repository如何为 JPA 存储库编写集成测试
【发布时间】:2021-07-28 07:01:59
【问题描述】:

我正在尝试对定义为的 JPA 存储库进行集成测试

@Repository
public interface TaskRepository extends JpaRepository<Task, Long>, JpaSpecificationExecutor<Task> {
    @Query("SELECT r from Task r where r.user.id = :userId AND r.date >= :startDate AND r.date <= :endDate")
    List<Task> getTasksBetweenDates(@Param("userId") long userId, @Param("startDate") LocalDate startDate, @Param("endDate") LocalDate endDate);
}

我做了如下测试:

@ExtendWith(SpringExtension.class)
@DataJpaTest
public class TaskRepositoryIntegrationTest {
    @Autowired
    private TaskRepository taskRepository;

     <test methods>
}

但是,IntelliJ 抱怨“无法自动装配。找不到 TaskRepository 类型的 bean”。

有人可以建议吗?

编辑:错误信息是:

java.lang.IllegalStateException: Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=...) with your test

    

【问题讨论】:

  • 你能用完整的堆栈跟踪显示错误消息吗
  • 添加了错误信息。
  • 检查 thisthis 链接应该会有帮助。

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


【解决方案1】:

在我的项目中,我们使用了 Spring Boot (v2.4.3)。以下代码可以很好地测试JPA repository

@SpringBootTest
public class PersonRepositoryTest {

  @Autowired
  PersonRepository personRepository;
...

【讨论】:

    猜你喜欢
    • 2019-07-10
    • 1970-01-01
    • 1970-01-01
    • 2018-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-21
    相关资源
    最近更新 更多