Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring not autowiring in unit tests with JUnit

Tags:

java

junit

spring

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"

like image 578
user1883212 Avatar asked Jul 12 '13 20:07

user1883212


People also ask

Can we use @autowired in test class?

To check the Service class, we need to have an instance of the Service class created and available as a @Bean so that we can @Autowire it in our test class. We can achieve this configuration using the @TestConfiguration annotation.

Why is JUnit test ignored?

The @Ignore annotation helps in this scenario. A test method annotated with @Ignore will not be executed. If a test class is annotated with @Ignore, then none of its test methods will be executed.

How do I turn on Autowiring in Spring?

In Spring, you can use @Autowired annotation to auto-wire bean on the setter method, constructor , or a field . Moreover, it can autowire the property in a particular bean. We must first enable the annotation using below configuration in the configuration file. We have enabled annotation injection.

Is Autowired annotation required?

Is @Autowired annotation mandatory for a constructor? No. After Spring 4.3 If your class has only single constructor then there is no need to put @Autowired .


1 Answers

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

like image 100
robert_difalco Avatar answered Oct 05 '22 11:10

robert_difalco