我试图测试我的Web应用程序,但是@autowired注释不起作用,并且该字段设置为null。请帮忙。
@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));
}
}
答案 0 :(得分:0)
当您在不扩展任何其他用@TestExecutionListeners({)}
注释的测试类的测试类上声明@TestExecutionListeners
时,实际上是在实际要使用组合时,告诉Spring仅加载您的Listener类。带有来自Spring的默认侦听器(例如DependencyInjectionTestExecutionListener
,它增加了对从ApplicationContext进行依赖项注入的支持)。
因此删除应通过自动装配加载所有必需的依赖项。
RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { AppConfig.class, WebSecurityConfig.class, MvcWebApplicationInitializer.class},
loader = AnnotationConfigContextLoader.class)
@PersistenceContext
@Transactional(transactionManager = "hibernateTransactionManager")
public class NewsDaoTest {