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"
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.
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.
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 mandatory for a constructor? No. After Spring 4.3 If your class has only single constructor then there is no need to put @Autowired .
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With