`
c_fanatic
  • 浏览: 66232 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

如何在单元测试中使用Spring 2.5的自动装配功能---转

阅读更多
Spring 2.5 ships with great support for integration testing through the classes in the org.springframework.test package. These classes allow you to dependency inject your test cases off of your existing Spring configuration, either by using your production Spring configuration file or one you've defined especially for the test case. This post explains how to annotate your JUnit 4 test cases to be autowired, but there's a lot more too the new spring-test.jar and it works with JUnit 3.8 also.
As setup for all the examples, let's assume there is a simple service that can return a String to you. Imaginative, huh?

Java 代码
public class MyService { 
 
   private final String name; 
 
   public MyService(String name) { 
       this.name = name; 
   } 
 
   public String getName() { 
       return name; 
   } 



This service is defined in a Spring XML configuration file as:

Xml代 码
<bean id="myService" class="org.sample.MyService" > 
    <constructor-arg value="simple service" /> 
</bean> 


To have Spring dependency inject our test case, we're going to have to annotate it with a little information. We'll use the standard JUnit @RunWith annotation to tell JUnit to use the Spring TestRunner, the Spring @ContextConfiguration annotation to indicate the TestCase needs injection, and the Spring @Autowired annotation to inject the MyService field by type.

Java 代码
@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration 
public final class SimpleAutowireTest { 
 
   @Autowired 
   private MyService service; 
 
   @Test 
   public void testServiceName() { 
       assertEquals("simple service", service.getName()); 
   } 
}  


There are a variety of ways to have Spring run your test. Besides SpringJUnit4ClassRunner.class there are also abstract TestCase objects you can inherit from, including some that will expose the ApplicationContext to you. By default, the spring configuration file for the test case will be [TestName]-context.xml. You can easily override this to point the test at your production configuration file. Also, the @Autowired annotation autowires the field by type. In the case of conflicts, you can specify the bean name using the @Qualifier annotation. Consider the following Spring configuration where there are two beans of type MyService in a file named applicationContext.xml:
Xml代 码
<bean id="deliveryService" class="org.sample.MyService" > 
    <constructor-arg value="delivery service" /> 
</bean> 
 
<bean id="accountingService" class="org.sample.MyService" > 
    <constructor-arg value="accounting service" /> 
</bean> 


The JUnit test now requires the @Qualifier field annotation and a configuration file location as an @ContextConfiguration parameter:

Java 代码
@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(locations = {"applicationContext.xml"}) 
public final class AdvancedAutowireTest { 
 
   @Autowired 
   @Qualifier("deliveryService") 
   private MyService service; 
 
   @Test 
   public void testServiceName() { 
       assertEquals("delivery service", service.getName()); 
   } 



To note: if you point the test to the production Spring configuration, then you're running integration tests and not unit tests. Integration tests are valuable and necessary, but are not always a wholesale replacement of unit tests. There's still value in isolation testing each of the components with mock dependencies. What I like about using Spring for the integration tests is that it validates the Spring mapping at test time. On my projects, we occasionally have the unit tests all passing but the Spring configuration contains a circular dependency, and we don't find out until the build hits QA. A Spring integration test pushes up error time to the test phase, when a developer can take quick action and long before QA is held up.

As is standard with JUnit, each test method runs within its own instance of the TestCase. However, the Spring TestRunner will only create one ApplicationContext for all the instances of the test method. This means that if you're test method destroys the state of a singleton bean, then downstream tests methods using that bean will fail. The way to work around this is to annotate your method with the @DirtiesContext annotation. This tells the Spring TestRunner to reload the context between test methods. For instance, these tests will pass when annotated, but fail when not:

Java 代码
@Autowired 
private MyConfigurableService service; 
 
@Test 
@DirtiesContext 
public void testServiceName1() { 
    assertEquals("configurable service", service.getName()); 
    service.setName("Updating Name"); 

 
@Test 
@DirtiesContext 
public void testServiceName2() { 
    assertEquals("configurable service", service.getName()); 
    service.setName("Updating Name"); 



There's a lot more in spring-test, but this is a good starting point. The transaction annotations look especially promising, including the ability to open and rollback transactions per method. The only reference I know for spring-test is the Javadoc at http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/test/package-summary.html. Those looking for a Spring starter lesson might consult the DZone RefCard.

The dependencies for spring-test are: junit, spring-context, spring-core, spring-beans, spring-tx, and commons-logging. A sample Gradle script for your build is at href="http://svn.assembla.com/svn/SampleCode/spring-test/build.gradle.
All the code for this post (including Gradle build script and IDEA project) is posted at http://svn.assembla.com/svn/SampleCode/spring-test/ and can be downloaded through subversion with the following command:

svn co http://svn.assembla.com/svn/SampleCode/spring-test
分享到:
评论

相关推荐

    Spring2.5-中文参考手册chm.zip

    除了XML配置外,开发者可以通过在类或方法上使用`@Autowired`、`@Qualifier`等注解来实现依赖自动装配。此外,还引入了基于类型和基于名称的自动装配,使得依赖管理更加简单。 2. **AOP增强**:Spring 2.5对AOP进行...

    spring2.5的所有jar包

    3. **XML配置增强**:在Spring 2.5中,XML配置文件得到了改进,引入了自动装配(autowiring)和注解支持,使得配置更加简洁。例如,`&lt;context:component-scan&gt;`标签可以扫描指定包下的所有注解组件。 4. **注解驱动...

    spring 2.5中文帮助文档

    通过阅读《Spring2.5-中文参考手册.chm》这份文档,开发者可以深入了解Spring 2.5的各种特性和用法,解决实际开发中遇到的问题,提升开发效率。文档不仅包含详细的API参考,还包含丰富的示例和最佳实践指导,是学习...

    精通spring2.5

    1. **依赖注入(Dependency Injection,DI)**:Spring 2.5在DI方面进行了优化,支持了基于注解的配置,使得开发者可以在类的内部使用`@Autowired`、`@Qualifier`等注解,无需XML配置就能完成依赖的自动装配,提高了...

    Spring2.5-Reference_zh_CN.txt

    在Spring2.5中,IoC容器支持通过XML配置文件或注解的方式定义和管理Bean之间的依赖关系。 #### 三、Bean定义与管理 - **Bean定义**:Spring框架中的Bean是应用程序的基本组成部分,它们通常代表业务实体或服务组件...

    spring2.5源码

    Spring Test模块在2.5版本中增加了对注解测试的支持,如`@ContextConfiguration`和`@Test`,使得单元测试和集成测试更加方便。 通过深入学习Spring 2.5的源码,开发者可以更好地理解Spring框架的设计思想和工作...

    真正的中文Spring2.5 API 兴奋!

    在测试方面,Spring2.5提供了`@ContextConfiguration`和`@Test`注解,使得单元测试和集成测试更加方便。`Mockito`和`EasyMock`等库的集成,使得模拟对象的创建和验证变得简单。 总的来说,Spring2.5中文版API的发布...

    spring-reference2.5中文参考文档.pdf

    - **测试**:Spring框架提供了强大的测试支持,包括模拟bean、自动装配等,有助于编写单元测试和集成测试。 总之,Spring框架2.5版本是一个重要的里程碑,它不仅巩固了Spring作为Java开发领域领导者的地位,还为...

    spring2.5 api

    Spring 2.5 引入了注解配置,允许开发者在类和方法级别使用注解,如 @Component、@Service、@Repository 和 @Controller,这些注解对应了传统的 XML 中的 `&lt;bean&gt;` 元素。此外,@Configuration 类可以替代 XML 配置...

    传智播客 spring2.5源代码_lib包

    这个"传智播客 spring2.5源代码_lib包"包含了Spring 2.5框架中的所有库文件,通过这些库,开发者可以研究Spring的内部实现,理解其工作原理,并学习如何在实际项目中应用。对于Java开发者来说,深入学习和理解Spring...

    Spring自动装配解析

    Spring 2.5引入了基于注解的配置,可以使用`@Autowired`注解在字段、setter方法或构造函数上,声明需要自动装配的依赖。此外,还可以结合`@Qualifier`注解来指定具体的bean实例,避免类型匹配的冲突。 5. 自动装配...

    Spring2.5架构图

    Spring 2.5 引入了大量的注解,如 `@Autowired`、`@Required`、`@Component`、`@Service`、`@Repository` 和 `@Controller` 等,这些注解简化了代码,使得开发者无需编写大量的 XML 配置就能实现组件扫描和自动装配...

    spring2.5相关包

    SpEL 可以在配置文件、注解以及编程中使用,增强了动态数据访问的能力。 7. **国际化支持**:Spring 2.5 提供了对 JSTL(JavaServer Pages Standard Tag Library)的更好支持,使得在 MVC 应用中实现多语言变得更加...

    Spring2.5-中文参考手册.rar

    通过XML配置或注解方式定义bean,IoC容器会自动装配这些bean,使得开发者无需在代码中进行硬编码的依赖查找。 2. **AOP**:Spring的另一个关键特性,它允许开发者将关注点分离,如日志、事务管理等,从核心业务逻辑...

    Spring2.5-中文参考手册

    Spring框架是Java应用程序开发中的一个核心组件,尤其在企业级应用中广泛使用。Spring2.5版本虽然相对较老,但其基本概念和设计原则对于理解后续版本甚至Spring Boot等现代框架至关重要。本手册将深入探讨Spring的...

    spring2.5-中文参考手册.pdf

    Spring 2.5版本是在Spring 2的基础上进行了大量的改进和增强,提供了更多的功能和更好的性能。 ### Spring 2.5新特性 1. **支持注解**:Spring 2.5引入了对Java 5的注解的支持,这使得配置变得更加简洁和易于维护...

    spring2.5-中文API

    而注解配置则是Spring 2.5版本之后逐渐流行起来的一种方式,通过在类或方法上添加特定的注解来实现自动装配等功能;基于Java的配置则是在Spring 3.0版本之后引入的新特性,允许开发者使用纯Java代码来替代XML配置...

    spring2.5-英文文档1

    这份文档详细介绍了Spring 2.5的主要改进和功能,适用于那些希望深入理解Spring框架的开发者。 1. 概览(Overview) Spring 2.5在设计时考虑了模块化和易用性,它提供了一种称为控制反转(IoC)的编程范式,通过...

    spring2.5中文api

    这个中文API文档是Spring框架2.5版本的中文版,旨在帮助中国开发者更方便地理解和使用Spring框架,提高开发效率,减少在查阅英文文档时的语言障碍。 Spring框架的核心特性包括依赖注入(Dependency Injection,DI)...

    spring2.5_学习笔记

    在Spring 2.5中,注解支持的增强使代码更简洁,例如`@Autowired`用于自动装配依赖,`@Qualifier`用于指定特定的bean。 二、AOP(面向切面编程) Spring 2.5在AOP方面也有显著提升。AOP允许开发者定义“切面”,...

Global site tag (gtag.js) - Google Analytics