Spring Test @ContextConfiguration

作者:範宗雲 来源:原创 发布时间:2015-04-19 归档:spring-test

开发环境 : JDK 7 Maven 3 Junit 4.11 Spring 4.1.5 Eclipse Luna
beans.xml
		    <beans xmlns="http://www.springframework.org/schema/beans"
			  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
			  xmlns:context="http://www.springframework.org/schema/context"
			  xsi:schemaLocation="http://www.springframework.org/schema/beans
			  http://www.springframework.org/schema/beans/spring-beans.xsd
			  http://www.springframework.org/schema/context
			  http://www.springframework.org/schema/context/spring-context.xsd">
			  
			  <context:annotation-config />
			  
			  <context:component-scan base-package="org.lychie" />
			  
			</beans>
		    
BusinessServiceImpl
		    @Service
			public class BusinessServiceImpl implements BusinessService {
			
				@Override
				public String provide() {
					return "business service";
				}
			
			}
		    
原来你可能是这样做的 :
		    public class BusinessServiceImplTest {
			
				private static BusinessService businessService;
				
				@BeforeClass
				public static void prepare() {
					ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
					businessService = context.getBean(BusinessService.class);
				}
				
				@Test
				public void testProvide() {
					String result = businessService.provide();
					System.out.println("---> " + result);
				}
			
			}
		    
现在你可以这样做的 :
		    @RunWith(SpringJUnit4ClassRunner.class)
			@ContextConfiguration("/beans.xml")
			public class BusinessServiceImplTest {
			
				@Autowired
				private BusinessService businessService;
				
				@Test
				public void testProvide() {
					String result = businessService.provide();
					System.out.println("---> " + result);
				}
			
			}
		    
SpringJUnit4ClassRunner 是 Spring 针对 Junit4 测试环境提供的扩展, 在 Junit4 测试环境中可以获得 Spring 上下文支持的好处。这样可以在 Junit4 测试环境中使用依赖注入以及执行事务等。
@ContextConfiguration 用于确定如何为集成测试环境装载 Spring 上下文, 典型的是 xml 配置文件的方式。
最后, 不要忘记引入 spring-test 依赖, 具体配置如下 :
pom.xml 配置
		    <properties>
			  <spring.version>4.1.5.RELEASE</spring.version>
			</properties>
			<dependencies>
			  <dependency>
			    <groupId>org.springframework</groupId>
			    <artifactId>spring-context</artifactId>
			    <version>${spring.version}</version>
			  </dependency>
			  <dependency>
			    <groupId>org.springframework</groupId>
			    <artifactId>spring-test</artifactId>
			    <version>${spring.version}</version>
			    <scope>test</scope>
			  </dependency>
			  <dependency>
			    <groupId>junit</groupId>
			    <artifactId>junit</artifactId>
			    <version>4.11</version>
			    <scope>test</scope>
			  </dependency>
			</dependencies>
		    

示例代码下载
SpringTestContextConfiguration.zip