Search code examples
javaspringspring-bootspring-data-jpaspring-boot-test

Configure Spring @DataJpaTest with custom base repository


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() {

        ...
    }
}

The base repository is registered using the @EnableJpaRepositories annotation.

@EnableJpaRepositories(value = "org.somebody.repository", repositoryBaseClass = SimpleCustomJpaRepository.class)

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> { ... }

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. 
}

How should I register a custom JpaRepository implementation in combination with a JPA repository integration test?


Solution

  • 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. 
    }