快速业务通道

spring junit测试 - 编程入门网

作者 佚名技术 来源 NET编程 浏览 发布时间 2012-06-14
ConfigLocations() {     String[] configLocations = { "file:WebContent/WEB-INF/applicationContext.xml"};     return configLocations;  }

AbstractXXXSpringContextTests就会根据根据getConfigLocations方法返回的context xml位置的数 组来加载并且对加载的Context提供缓存。 这是非常重要的,因为如果你在从事一个大项目时,启动时间 可能成为一个问题--这不是Spring自身的开销,而是被Spring容器实例化的对象在实例 化自身时所需 要的时间。例如,一个包括50-100个Hibernate映射文件的项目可能需要10-20秒的时间来加载上述的映射 文件,如果在运行每个 测试fixture里的每个测试案例前都有这样的开销,将导致整个测试工作的延时, 最终有可能(实际上很可能)降低效率。

在某种极偶然的情况下,某个测试可能“弄脏”了配置场所,并要求重新加载--例如改变一个bean 的定义或者一个应用对象的状态--你可以调用 AbstractDependencyInjectionSpringContextTests 上 的 setDirty() 方法来重新加载配置并在执行下一个测试案例前重建application context

当类 AbstractDependencyInjectionSpringContextTests(及其子类)装载你的Application Context 时,你可以通过Setter方法来注入你想要的来自context的bean,而不需要显式的调用 applicationContext.getBean(XXX)。因为AbstractDependencyInjectionSpringContextTests会从 getConfigLocations()方法指定的配置文件中帮你自动注入

spring junit测试(3)

时间:2011-11-02 blogjava Java蜘蛛人 --郑成桥

下面的例子就是通过setter方法来获得context里的ProductManager bean:

public class MyTest extends AbstractDependencyInjectionSpringContextTests {

    ProductManager productManager;

    public String[] getConfigLocations() {

        String[] configLocations = { "file:WebContent/WEB-INF/applicationContext.xml" 

};

        return configLocations;

    }

    public void testGetProduct() {

       assertEquals("tomson",productManager.getProductByName("tomson").getName());

    }

    //通过setter方法自动从context里注入productManager bean,而不用显示调用

applicationContext.getBean(XXX)

    public void setProductManager(ProductManager productManager) {

       this.productManager = productManager;

    }

}

但是如 果context里有多个bean都定义为一个类型(例如有多个bean都是ProductManager class类型 的),那么对这些bean就无法通过setter方法来自动依赖注入(因为有多个bean同一个类型,不知要自动 注入哪个)。在这种情况下 你需要显示的调用applicationContext.getBean(XXX)来注入。如:

public class MyTest extends AbstractDependencyInjectionSpringContextTests {

   ProductManager productManager;

   public String[] getConfigLocations() {

      String[] configLocations = { "file:WebContent/WEB-INF/applicationContext.xml" };

      return configLocations;

   }

   public void onSetUp() {

       productManager = (ProductManager) applicationContext.getBean("productManager");

   }

   public void testGetProduct() {

       assertEquals("tomson",productManager.getProductByName("tomson").getName());

   }

}

如果你的TestCase不使用依

凌众科技专业提供服务器租用、服务器托管、企业邮局、虚拟主机等服务,公司网站:http://www.lingzhong.cn 为了给广大客户了解更多的技术信息,本技术文章收集来源于网络,凌众科技尊重文章作者的版权,如果有涉及你的版权有必要删除你的文章,请和我们联系。以上信息与文章正文是不可分割的一部分,如果您要转载本文章,请保留以上信息,谢谢!

分享到: 更多

Copyright ©1999-2011 厦门凌众科技有限公司 厦门优通互联科技开发有限公司 All rights reserved

地址(ADD):厦门软件园二期望海路63号701E(东南融通旁) 邮编(ZIP):361008

电话:0592-5908028 传真:0592-5908039 咨询信箱:web@lingzhong.cn 咨询OICQ:173723134

《中华人民共和国增值电信业务经营许可证》闽B2-20100024  ICP备案:闽ICP备05037997号