无法使用Spring Boot Test测试自定义存储库

时间:2017-02-27 06:56:19

标签: spring-boot spring-data junit4 spring-boot-test

我正在使用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

1 个答案:

答案 0 :(得分:0)

在Spring Boot Test的Github上发布了同样的问题并得到了答复。请参阅this