作用:
减少测试中不停的构建Spring容器,如以下代码,就可以省略掉。
ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfiguration.class);
context.getBean("bean元素对象名",对应的字节码对象);
开发步骤:
- 在pom.xml文件中添加spring-test坐标依赖
- 在测试类上面添加注解@RunWith(SpringJunit4ClassRunner.class)该SpringJunit4Runner类由它帮我们创建Spring容器
- 在测试类上面添加注解@ContextConfiguration(“classpath:applicationContext.xml”)注意饿:此路径是一个类路径,也是一个相对路径
- 从容器中取出需要的bean元素 get(Bean)采用注解注入@AutoWired @Resource
- 测试是否成功
代码示例如下:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class UserTest {
@Test
public void test01(){
System.out.println("测试正在进行中。。。。");
}
}