在实际项目开发中经常会有单元测试,单元测试中经常会用类似这样的代码片段获取spring管理的bean
@Test public void testSendEmail(){ MessageService messageService = (MessageService) BeanFactory.getInstance().getBean("messageService"); messageService.send(); }
这样既不美观,又比较繁琐,spring引进了spring-test跟junit结合使用可以方便的得到spring bean
因为在项目中适用maven管理依赖,先在pom.xml中添加依赖
<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了,减少了繁琐的代码也增强了代码的可读性