首先采用了maven来部署所需要的jar包依赖
这里需要srping-context.jar,spring-test.jar,junit.jar,log4j.jar
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.14</version>
</dependency>
log4j.properties配置 放在classpath下
log4j.rootCategory=INFO, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %t %c{2}:%L - %m%n
log4j.category.org.springframework.beans.factory=DEBUG
新建一个AppConfig类
com.domain里面包括了各种需要的bean,besePackages是一个数组,所以可以提供多个包
@ImportResource 是部分的xml配置,这里由于很大程度上使用了anotation配置,所以xml文件里面并没有什么东西。
@Profile的作用在于如果在开发时进行一些数据库测试,希望链接到一个测试的数据库,以避免对开发数据库的影响。
@Configuration
@ComponentScan(basePackages = "com.domain")
@ImportResource(value = "TestCase_01.xml")
public class AppConfig {
@Bean(name = "dbService")
@Profile("dev")
public DBService mockDBService(){
return new MockDBService();
}
@Bean(name = "dbService")
@Profile("rc")
public DBService MysqlDBService(){
return new MysqlDBService();
}
}
在单元测试类里面
在使用所有注释前必须使用@RunWith(SpringJUnit4ClassRunner.class),让测试运行于Spring测试环境
@ContextConfiguration是注册配置,这里可以是特定java配置类 也可以配置xml路径
由于需要ApplicationContext 所以添加了一个属性,通过@Autowired让spring容器来自动转配
@ActiveProfiles激活某个测试方案
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = AppConfig.class)
@ActiveProfiles("dev")
public class TestCase_01 {
@Autowired
private ApplicationContext ctx;
@Test
public void test_case_011() {
ClientService staticClientService = ctx.getBean("staticClientService", ClientService.class);
ClientService noneStaticClientService = ctx.getBean("noneStaticClientService", ClientService.class);
System.out.println(staticClientService);
System.out.println(noneStaticClientService);
}
@Test
public void test_case012() {
SimpleMovieLister s01 = ctx.getBean("movieListerWithConstructor", SimpleMovieLister.class);
SimpleMovieLister s02 = ctx.getBean("movieListerWithProperty", SimpleMovieLister.class);
assertNotNull(s01);
assertNotNull(s02);
assertNotNull(s01.getMovieFinder());
assertNotNull(s02.getMovieFinder());
}
@Test
public void profileTest() {
DBService dbService = ctx.getBean(DBService.class);
assertEquals(3, dbService.count("select * from users"));
}
}