我已经实现了DAO接口,该接口扩展了JpaRepository。在一种实现中,我需要会话,因此我在sessionFactory中使用了@Autowired批注,这破坏了我的单元测试。如果我不将@Autowired与sessionFactory一起使用,则单元测试将正常工作,但是功能将失败。 这是我实现的带有文件名的代码。
TagDAO.java
package dao;
//All the imports
@Repository
public interface TagDAO extends JpaRepository<Tag, Integer> {
public List<Object[]> getTagsWithQuestionCount(Pageable pageable) throws SomeException;
public Long getTagCount() throws SomeException;
public Tag findByTagName(@Param("tagName") String tagName) throws SomeException;
public List<Object[]> getAllTagIdsAndNames() throws SomeException;
public Tag save(Tag tag);
}
TagDAOImpl.java
package dao.impl;
//All the imports
public class TagDAOImpl implements TagDAO {
@Autowired
private SessionFactory sessionFactory;
@PersistenceContext(unitName = "entityManagerFactory")
EntityManager entityManager;
/**
* {@inheritDoc}
*/
@Override
public Long getTagCount() throws RFPDatabaseException {
//implementation
}
}
/**
* {@inheritDoc}
*/
@Override
public Tag findByTagName(String tagName) throws RFPDatabaseException {
//implementation
}
@Override
public List<Object[]> getAllTagIdsAndNames() throws RFPDatabaseException {
//implementation
}
@Override
public List<Object[]> getTagsWithQuestionCount(Pageable pageable) throws RFPDatabaseException {
//implementation
}
}
@Override
public Tag save(Tag tag) {
Preconditions.checkNotNull(tag, NULL_TAG_MESSAGE);
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(tag);
session.getTransaction().commit();
return tag;
}
//Rest are todo because of the JpaRepository extends
@Override
public List<Tag> findAll(Sort sort) {
// TODO Auto-generated method stub
return null;
}
@Override
public List<Tag> findAll(Iterable<Integer> ids) {
// TODO Auto-generated method stub
return null;
}
//........
// A bunch of other methods
}
TagDAOImplTest.java
package dao.impl;
//All the imports
@RunWith(SpringJUnit4ClassRunner.class)
@ContextHierarchy({
@ContextConfiguration(classes = EntityManagerConfig.class),
@ContextConfiguration(locations = "classpath:applicationContext.xml")
})
public class TagDAOImplTest {
@Mock(name = "entityManager")
private EntityManager entityManagerMock;
@Mock
private CriteriaBuilder criteriaBuilderMock;
@Mock
private CriteriaQuery<Tag> criteriaQueryMock;
@Mock
private CriteriaQuery<Long> criteriaQueryMockForTagCount;
@Mock
private CriteriaQuery<Object[]> criteriaQueryMockForGetAllTagIdsAndNames;
@Mock
private Root<Tag> rootTagMock;
@Mock
private Path<Object> pathMock;
@Mock
private Expression<Long> expression;
@Mock
private Predicate predicateMock;
@Mock
private TypedQuery<Tag> typedQueryMock;
@Mock
private TypedQuery<Long> typedQueryMockForTagCount;
@Mock
private TypedQuery<Object[]> typedQueryMockForGetAllTagIdsAndNames;
@InjectMocks
private TagDAOImpl tagDAOImpl;
@Mock
private Tag tag;
@Rule
public ExpectedException thrown = ExpectedException.none();
/**
* This method initialize objects for {@link TagDAO} class.
*/
@Before
public void setup() {
tagDAOImpl = new TagDAOImpl();
MockitoAnnotations.initMocks(this);
when(entityManagerMock.getCriteriaBuilder()).thenReturn(criteriaBuilderMock);
}
// All the unit tests
}
beans.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="configLocation" value="classpath:hibernate.cfg.xml" />
</bean>
<bean id ="tagDAO" class ="dao.impl.TagDAOImpl"/>
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<import resource="beans.xml" />
<import resource="spring-dispatcher-servlet.xml" />
现在,如果我从TagDAOImpl单元中删除@Autowired,则单元测试将失败并出现以下错误
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124)
at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:83)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:117)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:230)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:228)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:287)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:289)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:247)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:538)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:760)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:460)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:206)
Caused by: java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124)
at org.springframework.test.context.MergedContextConfiguration.getParentApplicationContext(MergedContextConfiguration.java:438)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:117)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:60)
at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.delegateLoading(AbstractDelegatingSmartContextLoader.java:108)
at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.loadContext(AbstractDelegatingSmartContextLoader.java:251)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116)
... 25 more
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'tagDAOImpl': Unsatisfied dependency expressed through field 'sessionFactory': No qualifying bean of type [org.hibernate.SessionFactory] found for dependency [org.hibernate.SessionFactory]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.hibernate.SessionFactory] found for dependency [org.hibernate.SessionFactory]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:569)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:349)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:776)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:861)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:541)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:128)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:60)
at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.delegateLoading(AbstractDelegatingSmartContextLoader.java:108)
at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.loadContext(AbstractDelegatingSmartContextLoader.java:251)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116)
... 32 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.hibernate.SessionFactory] found for dependency [org.hibernate.SessionFactory]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1406)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1057)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1019)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:566)
... 50 more
如果删除@Autowired,我的功能将失败。我研究了很多类似问题的现有解决方案。没有任何帮助。有什么建议吗?
答案 0 :(得分:0)
如果我不将@Autowired与 sessionFactory。
您获得没有@Autowired
注释的NPE吗?我希望如此。
如果您需要在Spring上下文的sessionFactory
中使用TagDAOImpl
,那么显然需要某种类型的依赖注入。在测试中,您要么模拟您的bean,要么使用一个真实的bean,我认为正是您尝试做的,因为我看不到@Mock
的任何sessionFactory
。
所以我在applicationContext.xml
中注意到了您导入 beans.xml
。但是您有 Bean.xml
,我认为应该将其导入。希望它将解决您的问题。让我们知道不是这种情况。
答案 1 :(得分:0)
您尝试过
@ContextConfiguration(locations = {"classpath:**/applicationContext.xml",
})
在单元测试类上将applicationContext xml加载到测试用例中,以便您可以使用Bean。 这将创建类在运行时需要的依赖关系,因此您可能无法获得NPE
答案 2 :(得分:0)
您有:
@Before
public void setup() {
tagDAOImpl = new TagDAOImpl();
...
}
但是与此同时,您在此字段上有@InjectMocks
,该字段应该为您初始化tagDAOImpl
并注入提供的模拟。在setup
中,您实际上创建了TagDAOImpl
的全新实例,而没有注入任何bean。这可能是您的问题背后的原因。尝试在您的setup
方法中删除该字段的初始化。这可能会有所帮助。并告诉我们是否不是这种情况。无论哪种方式,创建该字段的另一个实例似乎都是多余的。