Spring not autowiring in unit tests with JUnit

JavaSpringJunit

Java Problem Overview


I test the following DAO with JUnit:

@Repository
public class MyDao {

    @Autowired
    private SessionFactory sessionFactory;

    // Other stuff here

}

As you can see, the sessionFactory is autowired using Spring. When I run the test, sessionFactory remains null and I get a null pointer exception.

This is the sessionFactory configuration in Spring:

<bean id="sessionFactory"
	class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
	<property name="dataSource" ref="dataSource" />
	<property name="configLocation">
		<value>classpath:hibernate.cfg.xml</value>
	</property>
	<property name="configurationClass">
		<value>org.hibernate.cfg.AnnotationConfiguration</value>
	</property>
	<property name="hibernateProperties">
		<props>
			<prop key="hibernate.dialect">${jdbc.dialect}</prop>
			<prop key="hibernate.show_sql">true</prop>
		</props>
	</property>
</bean>

What's wrong? How can I enable autowiring for unit testings too?

Update: I don't know if it's the only way to run JUnit tests, but note that I'm running it in Eclipse with right-clicking on the test file and selecting "run as"->"JUnit test"

Java Solutions


Solution 1 - Java

Add something like this to your root unit test class:

@RunWith( SpringJUnit4ClassRunner.class )
@ContextConfiguration

This will use the XML in your default path. If you need to specify a non-default path then you can supply a locations property to the ContextConfiguration annotation.

http://static.springsource.org/spring/docs/2.5.6/reference/testing.html

Solution 2 - Java

I had same problem with Spring Boot 2.1.1 and JUnit 4
just added those annotations:

@RunWith( SpringRunner.class )
@SpringBootTest

and all went well.

For Junit 5:

@ExtendWith(SpringExtension.class)

source

Solution 3 - Java

I'm using JUnit 5 and for me the problem was that I had imported Test from the wrong package:

import org.junit.Test;

Replacing it with the following worked for me:

import org.junit.jupiter.api.Test;

Solution 4 - Java

You need to use the Spring JUnit runner in order to wire in Spring beans from your context. The code below assumes that you have a application context called testContest.xml available on the test classpath.

import org.hibernate.SessionFactory;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;

import java.sql.SQLException;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.startsWith;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath*:**/testContext.xml"})
@Transactional
public class someDaoTest {

    @Autowired
    protected SessionFactory sessionFactory;

    @Test
    public void testDBSourceIsCorrect() throws SQLException {
        String databaseProductName = sessionFactory.getCurrentSession()
                .connection()
                .getMetaData()
                .getDatabaseProductName();
        assertThat("Test container is pointing at the wrong DB.", databaseProductName, startsWith("HSQL"));
    }
}

Note: This works with Spring 2.5.2 and Hibernate 3.6.5

Solution 5 - Java

Missing Context file location in configuration can cause this, one approach to solve this:

  • Specifying Context file location in ContextConfiguration

like:

@ContextConfiguration(locations = { "classpath:META-INF/your-spring-context.xml" })

More details

@RunWith( SpringJUnit4ClassRunner.class )
@ContextConfiguration(locations = { "classpath:META-INF/your-spring-context.xml" })
public class UserServiceTest extends AbstractJUnit4SpringContextTests {}

Reference:Thanks to @Xstian

Solution 6 - Java

You need to add annotations to the Junit class, telling it to use the SpringJunitRunner. The ones you want are:

@ContextConfiguration("/test-context.xml")
@RunWith(SpringJUnit4ClassRunner.class)

This tells Junit to use the test-context.xml file in same directory as your test. This file should be similar to the real context.xml you're using for spring, but pointing to test resources, naturally.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1883212View Question on Stackoverflow
Solution 1 - Javarobert_difalcoView Answer on Stackoverflow
Solution 2 - JavaMcinView Answer on Stackoverflow
Solution 3 - JavaCanerView Answer on Stackoverflow
Solution 4 - JavaMike RylanderView Answer on Stackoverflow
Solution 5 - JavaAbhijeetView Answer on Stackoverflow
Solution 6 - JavaTrueDubView Answer on Stackoverflow