我正在使用Spring Boot 1.4.4。按照Spring Boot Test文章进行单元测试。当我有自定义存储库时,测试无法正常运行,但失败并显示错误UnsatisfiedDependencyException: Error creating bean with name 'com.jay.UserRepositoryTest': Unsatisfied dependency expressed through field 'userRepository';
这是我的代码,
@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(){
...
}
}
但是我能够在没有任何配置更改的情况下使用Spring Boot测试以下Dao,
@Transactional
public interface UserDao extends CrudRepository<User, Long> {
User findByEmail(String email);
}
当我使用@SpringBootTest
时,我可以注入UserRepository
,但不能注入TestEntityManager
。