我将使用中文进行翻译,该段内容是关于编程的。
当我使用
我正在使用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
。