I am using Spring Boot 1.4.4. Followed the Spring Boot Test article for unit tests. When I have custom repositories, test is not working and fails with error UnsatisfiedDependencyException: Error creating bean with name 'com.jay.UserRepositoryTest': Unsatisfied dependency expressed through field 'userRepository';
Here is my code,
@Repository
@Transactional
public class UserRepository {
@Autowired
private EntityManager entityManager;
// sample code for custom repo. can be done easily in CrudRepo
public User findUser(String name){
TypedQuery<User> q = entityManager.createQuery("Select u from User u Where u.name = :name", User.class);
q.setParameter("name", name);
return q.getSingleResult();
}
}
@RunWith(SpringRunner.class)
@DataJpaTest
public class UserRepositoryTest {
@Autowired
private TestEntityManager entityManager;
@Autowired
private UserRepository userRepository;
@Test
public void findUserTest(){
...
}
}
But I am able to test the following Dao with Spring Boot without any config change,
@Transactional
public interface UserDao extends CrudRepository<User, Long> {
User findByEmail(String email);
}
When I am using @SpringBootTest
, I am able to inject UserRepository
, but not TestEntityManager
.
As described in the documentation, @DataJpaTest
will "configure Spring Data JPA repositories". Your UserRepository
isn't a Spring Data JPA repository so it isn't configured.
In the same section of the documentation it also explains that if you want to use TestEntityManager
with @SpringBootTest
, you can enable it by adding @AutoConfigureTestEntityManager
to your test class.
Most helpful comment
As described in the documentation,
@DataJpaTest
will "configure Spring Data JPA repositories". YourUserRepository
isn't a Spring Data JPA repository so it isn't configured.In the same section of the documentation it also explains that if you want to use
TestEntityManager
with@SpringBootTest
, you can enable it by adding@AutoConfigureTestEntityManager
to your test class.