---
title: "单元测试使用spring注解获取bean"
author: "weiguo21"
date: "2014-03-05T17:26:00Z"
tags: []
slug: "spring-bean"
draft: false
lastmod: "2014-06-06T09:38:42Z"
id: 2076535
url: "https://weiguo21.iteye.com/blog/2076535"
---

在实际项目开发中经常会有单元测试,单元测试中经常会用类似这样的代码片段获取spring管理的bean

1

2

3

4

5

`@Test`

`publicvoidtestSendEmail(){`

`MessageService messageService = (MessageService) BeanFactory.getInstance().getBean("messageService");`

`messageService.send();`

`}`

　这样既不美观,又比较繁琐,spring引进了spring-test跟junit结合使用可以方便的得到spring bean

　因为在项目中适用maven管理依赖,先在pom.xml中添加依赖

1

2

3

4

5

`<dependency>`

`<groupId>org.springframework</groupId>`

`<artifactId>spring-test</artifactId>`

`<version>${spring.version}</version>`

`</dependency>`

　绑定spring配置文件路径

[![复制代码](http://common.cnblogs.com/images/copycode.gif)]()

```
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:applicationContext.xml" })
public class BaseTest extends TestCase {
    protected Logger logger = LoggerFactory.getLogger(getClass());

}
在单元测试类中集成 BaseTest

```

public class PostServiceTest extends BaseTest {  
@Resource(name = "postService")  
private PostService postService;

```

```

@Test  
public void testQuery2LevelPostType() {  
Map&lt;Integer,Object&gt; map= postService.query2LevelPostType();  
System.out.println("data size:" + map.size());  
　　}  
}

这样就可以在单元测试中轻松获取spring bean了,减少了繁琐的代码也增强了代码的可读性

```
博客园地址:http://www.cnblogs.com/weiguo21/p/3582920.html

```

[![复制代码](http://common.cnblogs.com/images/copycode.gif)]()