title: Unit testing Services in Spring by Mocking DAO
body: <p>I am using Mockito to mock my DAOS and test my Service Layer. This is an example of what I've got:</p>
  
  <pre><code>@RunWith(SpringJUnit4ClassRunner.class)
  @ContextConfiguration(locations = { "classpath:/spring/programacion-service-test.xml" })
  public class ProgramacionServiceUnitTest {
  
      @Autowired
      private ProgramacionService programacionService;
  
      @InjectMocks
      @Autowired
      private IProgramacionDAO programacionDAO;
  
      private Mapper mapper = new DozerMapper();
  
      @Before
      public void init() {
  
      }
  
      // Probamos comprobando el id.
      @Test
      public void saveProgramacionTest() {
          ProgramacionDTO p = getEntityDTO();
          Mockito.when(programacionDAO.persist(Matchers.any(Programacion.class))).thenAnswer(new Answer&lt;Programacion&gt;() {
  
              @Override
              public Programacion answer(InvocationOnMock invocation) throws Throwable {
                  Programacion programacion = (Programacion) invocation.getArguments()[0];
                  programacion.setIdProgramacion(1L);
                  return programacion;
              }
          });
          try{
          programacionService.altaProgramacion(p);
          compareEntities(p, programacionService.getProgramacion(0L));
          }catch(Exception e){
              System.out.println("ERrOR:"+e.getMessage());
          }
      }
   (...)
  
  }
  </code></pre>
  
  <p>And this is my XML config:</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt;
  &lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jms="http://www.springframework.org/schema/jms"
      xmlns:context="http://www.springframework.org/schema/context" xmlns:mockito="http://www.mockito.org/spring/mockito" xmlns:aop="http://www.springframework.org/schema/aop"
      xmlns:cache="http://www.springframework.org/schema/cache"
      xsi:schemaLocation="http://www.springframework.org/schema/beans
          http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
          http://www.springframework.org/schema/context
          http://www.springframework.org/schema/context/spring-context-3.2.xsd
          http://www.springframework.org/schema/aop
          http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
          http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.2.xsd
          http://www.mockito.org/spring/mockito http://www.mockito.org/spring/mockito.xsd"&gt;
  
  
      &lt;!-- Enable component scanning for defining beans with annotations. --&gt;
      &lt;!-- END ANNOTATED CONFIGURATION --&gt;
      &lt;bean id="programacionDAO" class="org.mockito.Mockito" factory-method="mock"&gt;
          &lt;constructor-arg value="com.mypackages.dao.programacion.ProgramacionDAO" /&gt;
      &lt;/bean&gt;
  
      &lt;bean class="com.mypackages.service.ProgramacionService" /&gt;
  
  
      &lt;context:annotation-config /&gt;
      &lt;import resource="common-beans.xml" /&gt;
  
  
  
  &lt;/beans&gt;
  </code></pre>
  
  <p>The problem is -- I get an exception because I am not defining an EntityManagerFActory:</p>
  
  <pre><code>    java.lang.IllegalStateException: Failed to load ApplicationContext
      at org.springframework.test.context.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:91)
      at org.springframework.test.context.DefaultTestContext.getApplicationContext(DefaultTestContext.java:74)
      at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:116)
      at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:82)
      at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:212)
      at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:199)
      at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:251)
      at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
      at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:253)
      at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:216)
      at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:82)
      at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
      at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
      at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
      at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
      at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
      at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:60)
      at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:67)
      at org.junit.runners.ParentRunner.run(ParentRunner.java:292)
      at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:162)
      at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
      at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
      at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
      at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
      at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
      at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
  Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'programacionDAO': Injection of persistence dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [javax.persistence.EntityManagerFactory] is defined
      at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.postProcessPropertyValues(PersistenceAnnotationBeanPostProcessor.java:356)
      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1204)
      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:538)
      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
      at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
      at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:229)
      at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
      at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
      at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:725)
      at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
      at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
      at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:125)
      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:260)
      at org.springframework.test.context.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:63)
      at org.springframework.test.context.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:83)
      ... 25 more
  Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [javax.persistence.EntityManagerFactory] is defined
      at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.findDefaultEntityManagerFactory(PersistenceAnnotationBeanPostProcessor.java:559)
      at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.findEntityManagerFactory(PersistenceAnnotationBeanPostProcessor.java:515)
      at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor$PersistenceElement.resolveEntityManager(PersistenceAnnotationBeanPostProcessor.java:682)
      at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor$PersistenceElement.getResourceToInject(PersistenceAnnotationBeanPostProcessor.java:655)
      at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:164)
      at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
      at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.postProcessPropertyValues(PersistenceAnnotationBeanPostProcessor.java:353)
      ... 41 more
  </code></pre>
  
  <p>Is this right? I am using a Mock and my IProgramacionDAO has no reference to an entityManager, so to my understanding it shouldnt' be trying to inject any EntityManagerFactories. If I explicitly declare my EM, it works, but I feel like I am loading a Persistence Context that I don't really need...</p>