Use a Spring JPA repository exclusively for tests

Viewed 176

Using a repository in Spring is straightforward. For integration testing, I'd like to define a repository which provides test-specific methods without "polluting" the original repository.

Example

Let's say there is the following repo:

@Repository
public interface UserRepo extends JpaRepository<User, Long> {
}

For testing purposes I'd like to have something like the following but this repo shall only reside in a package in src/test.

@Repository
public interface UserTestRepo extends JpaRepository<User, Long> {

  boolean existsByEmail(String email);
}

When adding @Autowired public UserTestRepo userTestRepo in my test, then the following exception occurs:

No EntityManager with actual transaction available for current thread

Is it possible to have a distinct repo which is only accessible for testing?

1 Answers

You can have any number of repository you want (That won;t be ideal). Also try annotating your Class from where you are autowiring your repository @Transactional.

Related