Spring 单元测试配置
Spring 单元测试配置
增加相关依赖
<dependencies><dependency><groupId>org.springframeworkgroupId><artifactId>spring-testartifactId>dependency><dependency><groupId>org.springframeworkgroupId><artifactId>spring-contextartifactId>dependency><dependency><groupId>junitgroupId><artifactId>junitartifactId><scope>testscope>dependency>dependencies>
增加扫描包目录
@Configuration
@ComponentScan("pr.iceworld.fernando.demospringtest")
public class ConfigComponentScan {
}
定义相关service或者component
// 此类定义组件注解
@Service
public class ServiceA {public void doAction() {System.out.println("serviceA.doAction()");}
}
// 此类没有定义组件注解
public class ServiceB {public void doAction() {System.out.println("serviceB.doAction()");}
}
增加测试额外配置文件 如 spring-conf.xml
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd"><bean id="serviceB" class="pr.iceworld.fernando.demospringtest.service.ServiceB"/>
beans>
@RunWith(SpringJUnit4ClassRunner.class)
// 增加单元测试额外配置文件
@ContextConfiguration(locations = {"classpath:spring-conf.xml"})
public class TestBase {@AutowiredServiceB serviceB;@Testpublic void doAction() {AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(ConfigComponentScan.class);ServiceA serviceA = annotationConfigApplicationContext.getBean(ServiceA.class);serviceA.doAction();serviceB.doAction();}
}
serviceA.doAction()
serviceB.doAction()
那有什么方法可以让component scan 与 xml 配置在测试中同时加载,而不需要其中一个从ApplicationContext 中显示获取,使用 @ContextHierarchy
package org.springframework.test.context;
// ...
/*** ...* This annotation may be used as a meta-annotation to create custom composed annotations.* ...*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface ContextHierarchy {/*** A list of {@link ContextConfiguration @ContextConfiguration} instances,* each of which defines a level in the context hierarchy.* If you need to merge or override the configuration for a given level* of the context hierarchy within a test class hierarchy, you must explicitly* name that level by supplying the same value to the {@link ContextConfiguration#name* name} attribute in {@code @ContextConfiguration} at each level in the* class hierarchy. See the class-level Javadoc for examples.*/
ContextConfiguration[] value();
}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextHierarchy(value = {@ContextConfiguration(classes = ConfigComponentScan.class),@ContextConfiguration(locations = {"classpath:spring-conf.xml"})}
)
public class TestBase {@AutowiredServiceB serviceB;@AutowiredServiceA serviceA;@Testpublic void doAction() {serviceA.doAction();serviceB.doAction();}
}
正常输出结果
serviceA.doAction()
serviceB.doAction()
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
