Spring 单元测试配置

增加相关依赖

org.springframework

spring-test

org.springframework

spring-context

junit

junit

test

增加扫描包目录

@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

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans.xsd

">

@RunWith(SpringJUnit4ClassRunner.class)

// 增加单元测试额外配置文件

@ContextConfiguration(locations = {"classpath:spring-conf.xml"})

public class TestBase {

@Autowired

ServiceB serviceB;

@Test

public 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 {

@Autowired

ServiceB serviceB;

@Autowired

ServiceA serviceA;

@Test

public void doAction() {

serviceA.doAction();

serviceB.doAction();

}

}

正常输出结果

serviceA.doAction()

serviceB.doAction()

推荐文章

评论可见,请评论后查看内容,谢谢!!!
 您阅读本篇文章共花了: