单元测试使用spring注解获取bean
2014-03-05 17:26
537 查看
在实际项目开发中经常会有单元测试,单元测试中经常会用类似这样的代码片段获取spring管理的bean
这样既不美观,又比较繁琐,spring引进了spring-test跟junit结合使用可以方便的得到spring bean
因为在项目中适用maven管理依赖,先在pom.xml中添加依赖
绑定spring配置文件路径
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了,减少了繁琐的代码也增强了代码的可读性
因为在项目中适用maven管理依赖,先在pom.xml中添加依赖
@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了,减少了繁琐的代码也增强了代码的可读性
博客园地址:/article/6298470.html
相关文章推荐
- 单元测试使用spring注解获取bean
- 为何在新线程中使用注解获取不到Spring管理的Bean
- Spring4----使用注解方式配置bean和bean的属性
- 解决Jersey中使用@Resource注解无法获取bean
- spring @Bean注解的使用
- Spring启动后获取所有拥有特定注解的Bean
- 在SpringBoot中获取某个注解标记的`BeanName`
- 使用Spring注解,在静态方法中注入bean
- 不用注解,获取spring容器里的bean(ApplicaitonContext)
- spring aop使用注解从切面中获取参数
- spring boot 条件注解的使用@Conditional;@Conditional 可以根据条件,创建不同的bean,
- 使用监听获取spring容器的bean
- 【Spring】使用XML和注解装配Bean
- 使用Spring注解完成Bean的定义
- spring 在静态工具类中使用注解注入bean
- Spring(16)——使用注解进行bean定义
- Spring 学习之三 bean 使用注解 种类 作用域
- SSH下使用Spring注解自动注入bean
- Java - Spring中如何使用注解来配置Bean?有哪些相关的注解?
- spring注解与xml同时使用:bean命名问题及冲突