一键搞定内网穿透 联行号查询|开户行查询 在线工具箱 藏经阁
当前位置:首页 / 杂记 / 正文
Spring基于注解TestContext 测试框架测试用例
public class HomeBrandActionTest {
// @Autowired
// private AreaDao areaDao;

 @Test
 public void test() throws Exception {
  ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
  AreaDao areaDao = ctx.getBean(AreaDao.class);
  System.out.println(areaDao.findCount(Area.class));
 }
}
当运行这个测试类的test方法时,不能使用@Autowired方式得到areaDao,因为使用@Autowired时,必须是
spring容器中的bean通过@Autowired自动装配spring容器中的bean。
虽然new ClassPathXmlApplicationContext也启动spring了,但HomeBrandActionTest没有在spring容器中。
只能使用ApplicationContext的getBean方式得到这个bean。
可以像任何计划那样,给HomeBrandActionTest加上@Component注解,让spring启动将扫描时找到这个类并加载到容器中,然后
HomeBrandActionTest ctx = context.getBean(HomeBrandActionTest.class);
最后使用ctx执行它下面的使用了areaDao的方法,这样是可以的。



TestContext 测试框架可以在 JUnit 4.4 测试框架基础上运行起来
先添加依赖 
<dependency>
 <groupid>org.springframework</groupid>
 <artifactid>spring-test</artifactid>
 <version>4.1.6.RELEASE</version>
</dependency>
@ContextConfiguration(locations={"/applicationContext.xml"})
public class HomeBrandActionTest extends AbstractTransactionalJUnit4SpringContextTests {
 @Autowired
 private AreaDao areaDao;

 @Test
 public void test() throws Exception {
  System.out.println(areaDao.findCount(Area.class));
 }
}
标注了一个类级的 @ContextConfiguration 注解,这里 Spring将按指定的配置文件启动 Spring 容器,因为这个注解,后面的@Autowired才会生效。
HomeBrandActionTest 直接继承于 Spring 所提供的 AbstractTransactionalJUnit4SpringContextTests 的抽象测试类,
@Test 是 JUnit 4.4 所定义的注解
这种测试完后事务是自动回滚的,也就是说,测试插入数据时,插入完后,还会回滚,数据库的内容还是删除的,跟没插入一样。

更多可以查看这里
Spring基于注解TestContext 测试框架使用详解
http://www.zuidaima.com/share/1775574182939648.htm