Issue
I was trying to test my web application but @autowired annotation doesn't work and the field is set to null. Please help.
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { AppConfig.class, WebSecurityConfig.class, MvcWebApplicationInitializer.class},
loader = AnnotationConfigContextLoader.class)
@PersistenceContext
@Transactional(transactionManager = "hibernateTransactionManager")
@TestExecutionListeners({})
public class NewsDaoTest {
@Autowired
private NewsService newsService;
@Test
@Rollback(true)
public void testAddArticle() {
Article article = new Article();
article.setLink("test");
article.setTitle("Title");
assertTrue(newsService.create(article));
}
}
Solution
When you declare @TestExecutionListeners({)}
on a test class that does not extend any other test class annotated with @TestExecutionListeners
you are effectively telling Spring to load only your Listener classes, when you actually want to use a combination with the default listeners from Spring (e.g., the DependencyInjectionTestExecutionListener
which adds support for dependency injection of beans from the ApplicationContext).
so removing should load all required dependencies by autowired..
RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { AppConfig.class, WebSecurityConfig.class, MvcWebApplicationInitializer.class},
loader = AnnotationConfigContextLoader.class)
@PersistenceContext
@Transactional(transactionManager = "hibernateTransactionManager")
public class NewsDaoTest {
Answered By - kj007