将ehcache添加到DAO类后,Junit测试失败,无法在测试类中实例化DAO

时间:2017-08-23 13:24:45

标签: java spring jpa junit ehcache

我正在为我的项目添加ehcache而且我有一个单元测试类,我的DAO运行正常如果我在DAO上评论ehcache注释,如果我取消注释它就会失败,说明它无法自动装入DAO bean

这是我得到的错误:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.nicobrest.kamehouse.dao.DragonBallUserDaoJpaTest': Injection of autowired dependencies failed;
nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.nicobrest.kamehouse.dao.DragonBallUserDaoJpa com.nicobrest.kamehouse.dao.DragonBallUserDaoJpaTest.dragonBallUserDaoJpa;
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.nicobrest.kamehouse.dao.DragonBallUserDaoJpa] found for dependency:
expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true), @org.springframework.beans.factory.annotation.Qualifier(value=dragonBallUserDaoJpa)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214)
    at
...

我也试过,而不是在单元测试中自动装配DAO bean,自动装配应用程序上下文并按名称获取bean,当我这样做时,我得到一个例外,它不能将$ proxy32转换为我的DAO班。

java.lang.ClassCastException: com.sun.proxy.$Proxy32 cannot be cast to com.nicobrest.kamehouse.dao.DragonBallUserDaoJpa
    at com.nicobrest.kamehouse.dao.DragonBallUserDaoJpaTest.setUp(DragonBallUserDaoJpaTest.java:71)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
    at 
...

这些是相关文件:

的applicationContext.xml

...
<cache:annotation-driven cache-manager="cacheManager"/>
<import resource="applicationContext-persistence.xml" />

<!-- Ehcache configuration -->
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
  <property name="cacheManager" ref="ehcache" />
</bean>

<bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
  <property name="configLocation" value="classpath:ehcache.xml" />
  <property name="shared" value="true" />
</bean>

<!-- Example endpoints beans -->
<bean id="dragonBallUserService" class="com.nicobrest.kamehouse.service.DragonBallUserService">
  <property name="dragonBallUserDao" ref="dragonBallUserDaoJpa" />
</bean>

<bean id="dragonBallUserDaoJpa" class="com.nicobrest.kamehouse.dao.DragonBallUserDaoJpa">
  <property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
...

DragonBallUserDaoJpaTest.java

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:applicationContext.xml" })
public class DragonBallUserDaoJpaTest {

private static final Logger LOGGER 
LoggerFactory.getLogger(DragonBallUserDaoJpaTest.class);

@Autowired
@Qualifier("dragonBallUserDaoJpa")
private DragonBallUserDaoJpa dragonBallUserDaoJpa;
...
@Test
public void createDragonBallUserTest() {

  DragonBallUser dragonBallUser = new DragonBallUser(null, "vegeta", "vegeta@dbz.com", 49, 40,
      1000);

  try {
    assertEquals(0, dragonBallUserDaoJpa.getAllDragonBallUsers().size());
    dragonBallUserDaoJpa.createDragonBallUser(dragonBallUser);
    assertEquals(1, dragonBallUserDaoJpa.getAllDragonBallUsers().size());
    dragonBallUserDaoJpa
        .deleteDragonBallUser(dragonBallUserDaoJpa.getDragonBallUser("vegeta").getId());
  } catch (KameHouseBadRequestException | KameHouseNotFoundException e) {
    e.printStackTrace();
    fail("Caught unexpected exception.");
  }
}
...

DragonBallUserDaoJpa.java

public class DragonBallUserDaoJpa implements DragonBallUserDao {

@Autowired
private EntityManagerFactory entityManagerFactory;
...
@CacheEvict(value = { "getAllDragonBallUsersCache" }, allEntries = true)
public Long createDragonBallUser(DragonBallUser dragonBallUser) {

  EntityManager em = getEntityManager();
  try {
    em.getTransaction().begin();
    em.persist(dragonBallUser);
    em.getTransaction().commit();
  } catch (PersistenceException pe) {
    ...
  } finally {
    em.close();
  }
  return dragonBallUser.getId();
}
...

我不知道还有什么可以尝试,有什么想法吗?

我正在使用Spring 4.2.4.RELEASE,Hibernate 5.1.0.Final,Hibernate JPA 1.0.0.Final,ehcache 2.9.0,JUnit 4.12。

这肯定与ehcache有关,因为注释注释可以在测试类中自动装配DAO,并且单元测试通过但是我试了好几个小时而无法解决它。

谢谢!

2 个答案:

答案 0 :(得分:2)

第一个错误是因为您尝试注入DragonBallUserDaoJpa而不是DragonBallUserDao。为了能够添加缓存层,Spring在您的类上创建了一个代理。此代理实现类(DragonBallUserDao)的接口,然后委托给实际的类(DragonBallUserDaoJpa)。

检索bean时遇到同样的问题。由于代理只是实现了接口,因此您无法将其强制转换为实现。所以ClassCastException

所以,如果你在考试中这样做(你不需要限定词)

@Autowired
private DragonBallUserDao dragonBallUserDao;

应该这样做。

另一种解决方案(但我认为它没有用)是强制Spring使用cglib来创建代理。这样,您的代理确实将延伸到具体类。你需要这样的东西:<aop:aspectj-autoproxy proxy-target-class="true" />

最后,你也可以摆脱界面,因为我非常怀疑你有很多这个DAO的实现。所以界面没用,只是添加噪音。删除它会强制Spring创建一个cglib代理,因为没有可用的接口。

答案 1 :(得分:0)

你的junit没有加载你的spring conf xml。

试试这个:

@ContextConfiguration(locations = {
    "classpath:pathTo/applicationContext.xml"})

编辑:尝试删除限定符和/或在bean创建中添加name属性