1.使用原因
(1)如果按照junit测试方法的流程,每执行一个测试方法都会创建一个spring容器,这就意味着有多少个测试方法spring容器就会被出事后多少次。
虽然初始化spring容器的速度并不慢,但是可能spring容器中配置了hibernate等,这样的话就会非常影响性能。
然而使用spring的测试工具,spring容器只会初始化一次
(2)一般在单元测试中都会使用ctx.getBean这样的方法从spring容器中获取需要测试的目标bean,并还需要使用强制转换。
使用spring的测试工具,测试用例中的属性会被自动填充spring容器中对应的bean(当然还是需要autowire)
2.依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>3.2.3.RELEASE</version>
<scope>test</scope>
</dependency>
3.配置
@RunWith(SpringJUnit4ClassRunner.class) //使用junit4进行测试
@ContextConfiguration
({"/app*.xml","/spring/app*.xml","/spring/service/app*.xml"}) //加载配置文件
public class BaseJunit4Test {
}
4.例子
@RunWith(SpringJUnit4ClassRunner.class) //使用junit4进行测试
@ContextConfiguration ({"/applicationContext.xml"})
public class TestSpringTest {
@Autowired
private Person person;
@Test
public void test() {
System.out.println(person.getName());
}
}