`
weiguo21
  • 浏览: 17279 次
  • 性别: Icon_minigender_1
  • 来自: 上海
文章分类
社区版块
存档分类
最新评论

单元测试使用spring注解获取bean

 
阅读更多

在实际项目开发中经常会有单元测试,单元测试中经常会用类似这样的代码片段获取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配置文件路径

复制代码
@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<Integer,Object> map= postService.query2LevelPostType();
System.out.println("data size:" + map.size());
  }
}

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

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

复制代码
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics