1

I am using Mockito to mock my DAOS and test my Service Layer. This is an example of what I've got:

@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<Programacion>() {

            @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());
        }
    }
 (...)

}

And this is my XML config:

<?xml version="1.0" encoding="UTF-8"?>
<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">


    <!-- Enable component scanning for defining beans with annotations. -->
    <!-- END ANNOTATED CONFIGURATION -->
    <bean id="programacionDAO" class="org.mockito.Mockito" factory-method="mock">
        <constructor-arg value="com.mypackages.dao.programacion.ProgramacionDAO" />
    </bean>

    <bean class="com.mypackages.service.ProgramacionService" />


    <context:annotation-config />
    <import resource="common-beans.xml" />



</beans>

The problem is -- I get an exception because I am not defining an EntityManagerFActory:

    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

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...

MichelReap
  • 5,630
  • 11
  • 37
  • 99
  • You should post a full stacktrace and try to narrow down the issue. Also can't you just use a regular instance of your services for tests (do you really need spring)? –  Dec 18 '14 at 16:23
  • related: http://stackoverflow.com/questions/2457239/injecting-mockito-mocks-into-a-spring-bean –  Dec 18 '14 at 16:23
  • @RC just posted full StackTrace. Do I need Spring? Maybe I don't, but then I lose DI – MichelReap Dec 18 '14 at 16:28
  • I meant do you need spring **for the tests** –  Dec 18 '14 at 16:32
  • Well okay, probably not, but my problem is still there isnt it? – MichelReap Dec 18 '14 at 16:49
  • 1
    You are mocking a class not an interface. Your XML is mocking `com.mypackages.dao.programacion.ProgramacionDAO` which is the class not the interface. The class has a reference to an entity manager and will still be scanned for annotations. – M. Deinum Dec 18 '14 at 18:11
  • Assuming commons-beans.xml contains the bean definitions for hibernate session factory and other details, please post it so that the root cause could be determined. – Andy Dufresne Dec 19 '14 at 04:19
  • @AndyDufresne it doesn't -- That's the point. I shouldn't be declaring it since I am mocking the DAO. There should be no reference to Hibernate at all since I am working against interfaces – MichelReap Dec 19 '14 at 08:21
  • Then it means that there is some problem in your spring beans scanning. How is your package structure? Can you update your post with this? – Andy Dufresne Dec 19 '14 at 09:18
  • I don't define any more beans on my test app context than those shown on the XML I posted. Common-bean.xml just declares some application config properties (loading a properties file, etc.) – MichelReap Dec 19 '14 at 12:44

0 Answers0