【发布时间】:2017-12-25 12:26:14
【问题描述】:
我在 Spring 项目中工作,我想使用 JUnit 创建一个单元测试,但我得到空指针异常,这是我的代码:
我在我的项目 (A) 中创建测试:
@RunWith( SpringJUnit4ClassRunner.class )
@ContextConfiguration(locations = {"classpath*:**/applicationContext.xml"})
public class EditionArticleTest {
@Autowired
private ArticleService articleService ;
@Test
public void testfindArticleByNum()
throws Exception
{
//this line return null pointer Exception
Article article = articleService.findArticle("AA0045");
}
}
问题是我的服务的实现依赖于位于其他项目 (B) 中的 bean,如下所示:
public class ArticleServiceImpl implements articleService {
//the implementation of this bean exists in an other project
private ArticleFinder articleFinder ;
}
所以我在这一行得到了错误:
@Override
public Article findArticle( String numArticle )
{
//iget the null pointer exception in this line because spring can't
//instantiate the beans articleFinder
return articleFinder.findByNumArticle( numArticle );
}
请问您有什么建议可以解决这个问题并强制 spring 自动注入位于其他项目中的所有相关 bean。
问候。
【问题讨论】:
-
其他项目有办法导入它的bean吗?像
@Configurationclass 什么的?我认为这是因为 spring 没有扫描其他项目的 bean。您可以发布您的applicationContext.xml文件吗? -
嗨@GuySmorodinsky 谢谢你的时间,是的,每个项目都有它的applicationContext.xml 所以我的项目(A)无法扫描项目(B)中的applicationContext.xml 所以这就是为什么它找不到 bean
标签: java spring spring-mvc junit