Configuring Junit + spring + hibernate 4 + maven: Null pointer getting session

I hope someone can help me. I'm new on this and I'm really confusing right now. I google a lot but I'm still very confused. After going through several errors... I'm stuck in a nullPointerException.

I have a service and its implementation:

@Controller("PollService")
@Transactional
@Service
public class PollServiceImpl  extends BaseServiceImpl implements PollService {

@Resource(name="PollRepository")
private PollRepository repository;

   // etc..
}

The repository implementation:

@Repository("PollRepository")
@Transactional
public class PollRepositoryImpl extends BaseEntityRepositoryImpl implements PollRepository{ 
 //some code...
}

Then my test class:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration (locations = {"file:src/test/resources/applicationContext.xml"})
@TransactionConfiguration(transactionManager="transactionManager", defaultRollback=false)
@Transactional
public class PollRepositoryTest extends AbstractTransactionalJUnit4SpringContextTests {

   public PollRepositoryTest(){
     super();
   }

@Resource
protected SessionFactory sessionFactory;

Session session = sessionFactory.getCurrentSession();

@Resource
private PollService pollService;

    @Rollback(true)
    @Test
    public void testSaveSomething() throws Exception  {/** ... **/ }

}

And when I run it I have this stacktrace, NullPointer in : Session session = sessionFactory.getCurrentSession();

StackTrace:

java.lang.NullPointerException
    at com.myApp.package.repository.test.PollRepositoryTest.<init>(PollRepositoryTest.java:51)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
    at org.junit.runners.BlockJUnit4ClassRunner.createTest(BlockJUnit4ClassRunner.java:187)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:210)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:288)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:290)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
    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:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
    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:467)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)

My testApplicationContext.xml is:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:faces="http://www.springframework.org/schema/faces"
    xmlns:int-security="http://www.springframework.org/schema/integration/security"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:sec="http://www.springframework.org/schema/security"
    xsi:schemaLocation="http://www.springframework.org/schema/integration/security http://www.springframework.org/schema/integration/security/spring-integration-security-2.0.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
        http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
        http://www.springframework.org/schema/faces http://www.springframework.org/schema/faces/spring-faces-2.0.xsd
        http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <context:annotation-config />

    <bean id="logs" class="org.apache.log4j.Logger" factory-method="getLogger">
        <constructor-arg type="java.lang.String" value="my.Logger" />
    </bean>

    <!-- Enables the Spring MVC @Controller programming model -->
    <tx:annotation-driven transaction-manager="transactionManager" />

    <bean class="com.myApp.util.PersistenceUnitEntityScanner"
        name="persistenceEntityScanner">
        <constructor-arg value="com.myApp.entities" />
    </bean>

    <bean id="dataSource" name="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="org.postgresql.Driver" />
        <property name="url" value="jdbc:postgresql://localhost:5432/aName" />
        <property name="username" value="user" />
        <property name="password" value="pass" />
    </bean>

    <bean id="sessionFactory" name="sessionFactory"
      class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
      <property name="dataSource" ref="dataSource" />
       <property name="configurationClass">
        <value>org.hibernate.cfg.AnnotationConfiguration</value>
        </property>
      <property name="entityPackages">
        <list>
            <value>com.myApp.entities</value>
        </list>
      </property>
      <property name="schemaUpdate">
        <value>true</value>
      </property>
      <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
            <prop key="hibernate.show_sql">true</prop>
       </props>
      </property>
     </bean>

    <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager" name="transactionManager">
      <property name="sessionFactory">
            <ref local="sessionFactory" />
        </property>
    </bean>

</beans>

And in my pom.xml I have:

        <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>3.2.1.RELEASE</version>
        <optional>true</optional>
        </dependency>

        <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-expression</artifactId>
        <version>4.0.0.RELEASE</version>
        </dependency>

        <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>3.2.1.RELEASE</version>
        </dependency>

        <dependency>
           <groupId>org.springframework</groupId>
           <artifactId>spring-test</artifactId>
           <version>3.1.1.RELEASE</version>
           <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.jboss.spec</groupId>
            <artifactId>jboss-javaee-6.0</artifactId>
            <version>3.0.2.Final</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>

        <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.10</version>
        <type>jar</type>
        <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>3.2.4.RELEASE</version>
        <exclusions>
            <exclusion>
                <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            </exclusion>
        </exclusions>
        </dependency>

        <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>3.2.4.RELEASE</version>
        </dependency>
        <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>3.2.4.RELEASE</version>
        </dependency>               
        <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-tx</artifactId>
        <version>3.2.4.RELEASE</version>
        </dependency>

        <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
        <version>3.2.4.RELEASE</version>
        </dependency>

        <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-web</artifactId>
        <version>3.1.4.RELEASE</version>
        </dependency>

        <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-taglibs</artifactId>
        <version>3.1.4.RELEASE</version>
        </dependency>

        <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-config</artifactId>
        <version>3.1.4.RELEASE</version>
        </dependency>

        <dependency>
        <groupId>org.springframework.social</groupId>
        <artifactId>spring-social-core</artifactId>
        <version>1.0.3.RELEASE</version>
        </dependency>

        <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>4.1.7.Final</version>
        <exclusions>
                <exclusion>
            <artifactId>xml-apis</artifactId>
            <groupId>xml-apis</groupId>
            </exclusion>
            <exclusion>
                    <groupId>net.sf.ehcache</groupId>
                    <artifactId>ehcache</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <scope>provided</scope>
        <version>4.1.7.Final</version>
        </dependency>

        <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-search</artifactId>
        <version>4.4.2.Final</version>
        <exclusions>
                <exclusion>
                <groupId>net.sf.ehcache</groupId>
                <artifactId>ehcache</artifactId>
                </exclusion>
        </exclusions>
        </dependency>

        <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-validator</artifactId>
        <scope>provided</scope>
        <optional>false</optional>
        <exclusions>
                <exclusion>
                    <groupId>net.sf.ehcache</groupId>
                    <artifactId>ehcache</artifactId>
                </exclusion>
        </exclusions>
        </dependency>

Well... I will be very gratefull if someone can help me to understand all this! And sorry if there are a lot of errors.

UPDATE

Thanks for your answers, I really appreciate it. Now I can see some light.

  1. Well, I change the versions of spring dependencies. They are all in 4.0.0.RELEASE now.
  2. Plus I remove @Controller("PollService") in PollServiceImpl like said Boris Treukhov.
  3. And I did some fixes in my test class and now it is:

    @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration (locations = {"file:src/test/resources/applicationContext.xml"}) @TransactionConfiguration(transactionManager="transactionManager", defaultRollback=false) @Transactional public class PollRepositoryTest {

    @Resource
    protected SessionFactory sessionFactory;
    
    private Session session;
    
    @Before
    public void setUpSession() throws Exception {
      session = sessionFactory.getCurrentSession();
    }
    
    @Autowired
    private PollService pollService;
    
    @Rollback(true)
    @Test
    public void testSaveQuizPreference() throws Exception  { /**...**/}
    

And now it throws this stacktrace:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.myApp.repository.test.PollRepositoryTest': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.myApp.services.PollService com.myApp.repository.test.PollRepositoryTest.pollService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.myApp.services.PollService] 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)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:292)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:384)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:110)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:326)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:212)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:232)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:89)
    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:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:175)
    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:467)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.myApp.services.PollService com.myApp.repository.test.PollRepositoryTest.pollService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.myApp.services.PollService] 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)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:508)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289)
    ... 26 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.myApp.services.PollService] 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)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1100)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:960)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:855)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:480)
    ... 28 more

This mean I need to create the bean in my applicationContext? Because I thing putting in my appContext.xml is used to avoid create beans in the xml. I hope you can help me with this issue. And really thanks for your answers.

Answers


Where is the line Session session = sessionFactory.getCurrentSession();? If it's a simple member variable, then it will be executed at construction time. But the resources aren't injected until later. So move that line into a method annotated with @Before.

private Session session;

@Before
public void setUpSession() throws Exception {
  session = sessionFactory.getCurrentSession();
}

why are you extending AbstractTransactionalJUnit4SpringContextTests ?

A typical test for me (while testing spring-mvc) look like this:

WebControllerTest.java

import org.junit.Before;
import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import com.***.hkb.salesweb.Application;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebAppConfiguration
public abstract class WebControllerTest {

    @Autowired
    CustomerController customerController;

    protected MockMvc mockMvc;

    @Autowired
    WebApplicationContext wac;

    @Before
    public void setup() {

        // Process mock annotations
        MockitoAnnotations.initMocks(this);
        // Setup Spring test in webapp-mode (same config as spring-boot)
        this.mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
    }
}

CustomerControllerTest.java

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

import org.junit.Test;

public class CustomerControllerTest extends WebControllerTest {

    @Test
    public void testLoadCustomerPage() throws Exception{
        this.mockMvc.perform(get("/customer")).andExpect(status().isOk());

    }
}

Also: i would advice to use spring-boot and its auto-config to get up and running. Lets you use spring without all the hassle of getting every config right the first time.

The learning-curve is quite steep for spring (i am still a beginner myself :))


General suggestion

Runner vs extending SpringContextTests

When are you using runner

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@TransactionConfiguration
@Transactional

then extending AbstractTransactionalJUnit4SpringContextTests is not required.

Note: this class (AbstractTransactionalJUnit4SpringContextTests) serves only as a convenience for extension. If you do not wish for your test classes to be tied to a Spring-specific class hierarchy, you may configure your own custom test classes by using SpringJUnit4ClassRunner, @ContextConfiguration, @TestExecutionListeners, @Transactional, etc.


Use @Before for instantiating fields

Fields should be instantiated inside @Before like @Paul Hicks said or inplace, where they are declared if this is possible.

@Resource
protected SessionFactory sessionFactory;

Session session;

@Before
public void setup(){
    session = sessionFactory.getCurrentSession();
}

Invoking super() from SpringContextTests

This code is not required

public PollRepositoryTest(){
   super();
}
Mixing spring versions

Don't mix spring version in one project!

    <artifactId>spring-expression</artifactId>
    <version>4.0.0.RELEASE</version>

    <artifactId>spring-beans</artifactId>
    <version>3.2.1.RELEASE</version>

    <artifactId>spring-test</artifactId>
    <version>3.1.1.RELEASE</version>

Use only one version, good idea is to create ${spring.version} property.


Need Your Help

MacOS X, C: shm_open fails with errno 13 Permission denied on subsequent runs

macos semaphore shared-memory mmap

I'm trying to use shm_open and mmap and a semaphore to share a block of memory between two processes on MacOS X.