使用自定义基础存储库配置 Spring @DataJpaTest [英] Configure Spring @DataJpaTest with custom base repository
问题描述
让我们假设一个自定义基础 JpaRepository 实现如下.
Let's assume a custom base JpaRepository implementation like the following.
public class SimpleCustomJpaRepository<T, ID extends Serializable> extends SimpleJpaRepository<T, ID> implements CustomJpaRepository<T, ID> {
@Override
public List<T> findAllCustom() {
...
}
}
使用 @EnableJpaRepositories
注释注册基础存储库.
The base repository is registered using the @EnableJpaRepositories
annotation.
@EnableJpaRepositories(value = "org.somebody.repository", repositoryBaseClass = SimpleCustomJpaRepository.class)
我应该如何为扩展 CustomJpaRepository
接口的 UserRepository
配置集成测试,并为此使用自定义基本实现?
How should I configure a integration test for the UserRepository
that's extending the CustomJpaRepository
interface and should therefor use the custom base implementation?
public interface UserRepository extends CustomJpaRepository<User, Long> { ... }
当前使用的集成测试失败,出现 org.springframework.data.mapping.PropertyReferenceException: No property findAllCustom found for type User!
.实际上,它无法加载 ApplicationContext
,因为我的自定义基础存储库实现在集成测试期间未注册,因此未找到 findAllCustom
的实现.
The currently used integration test fails with org.springframework.data.mapping.PropertyReferenceException: No property findAllCustom found for type User!
. Actually it failed to load the ApplicationContext
because my custom base repository implementation is not registered during integration test and therefor no implementation for findAllCustom
was found.
@ExtendWith(SpringExtension.class)
@DataJpaTest
class UserRepositoryTest {
@Autowired
private UserRepository userRepository.
}
我应该如何结合 JPA 存储库集成测试注册自定义 JpaRepository
实现?
How should I register a custom JpaRepository
implementation in combination with a JPA repository integration test?
推荐答案
我还是无法解释问题的原因,但是手动配置JPA已经解决了我的问题.
I still can't explain the cause of the problem, but manually configuring the JPA has solved my problem.
@TestConfiguration
@EnableAutoConfiguration(exclude = {JpaRepositoriesAutoConfiguration.class})
@EnableJpaRepositories(value = "org.somebody.repository", repositoryBaseClass = SimpleCustomJpaRepository.class)
public class JpaTestConfig {
...
}
我刚刚在我的测试中导入了这个额外的配置类,它就像一个魅力.
I just imported this additional configuration class in my tests and it works like a charm.
@ExtendWith(SpringExtension.class)
@DataJpaTest
@Import(JpaTestConfig.class)
class UserRepositoryTest {
@Autowired
private UserRepository userRepository.
}
这篇关于使用自定义基础存储库配置 Spring @DataJpaTest的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!