Spring框架下的单元测试方法

发表于:2014-8-28 11:04

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:keep--moving    来源:51Testing软件测试网采编

  介绍在Spring的框架下,做单元测试的两种办法。
  一、使用spring中对Junit框架的整合功能
  除了junit4和spring的jar包,还需要spring-test.jar。引入如下依赖:
<span style="font-size:18px;"><span style="white-space:pre">        </span><dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>3.1.1.RELEASE</version>
</dependency></span>
  然后测试类需要继承自AbstractJUnit4SpringContextTests,这样就可以在测试类中使用注解简单的注入需要的bean了。
<span style="font-size:18px;"><span style="color:#ff0000;">@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:applicationContext.xml"})</span>
public class ReadDaoImplTest extends<span style="color:#ff0000;"> AbstractJUnit4SpringContextTests</span>{
@Resource ReadDao readDao;
@Test
public void getListTest(){
List<Client> clientList = readDao.getList("client.test", null);
for(Client c:clientList){
System.out.println(c.getVersionNum());
}
}
}
</span>
  二、手动加载spring的配置文件,并启动spring容器
public class ReadDaoImplTest {
public  static void main(String[] args){
ClassPathXmlApplicationContext context = <span style="color:#ff0000;">new ClassPathXmlApplicationContext("applicationContext.xml");</span>
context.start();
ReadDao fqaService = (ReadDao) context.getBean("readDao");
System.out.println(fqaService);
}
}
  用这种方式测试,只需要Ctrl+F11就行了
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号