6.spring单元测试
使用spring的单元测试:
测试代码为:
@ContextConfiguration(locations = "classpath:ioc.xml")
@RunWith(SpringJUnit4ClassRunner.class)
public class Test {
@Autowired
BookServlet bookServlet;
@org.junit.Test
public void tes1() {
System.out.println(bookServlet);
}
}
1.导包
<dependency>
<groupId>junit</groupId>----------------->junit的测试包
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>3.0.6.RELEASE</version>---------->版本号必须和spring的其他包的版本相同,不然会有包冲突,报错
</dependency>
2.@ContextConfiguration(locations = "classpath:ioc.xml")指定spring配置文件的位置
3.@RunWith(SpringJUnit4ClassRunner.class)指定用那种驱动去进行单元测试,默认是junit
SpringJUnit4ClassRunner.class:是使用spring的单元测试模块进行带了@Test标的测试方法
好处:我们在获取组件的时候不用ioc.getBean("id值")
而是采用:
@Autowired
BookServlet bookServlet;
即可!