单元测试的错误示范:
当启动ioc容器时就会扫描所有组件,@Component就会被扫描到重复加载ioc容器无限套娃。
1、导包
Spring的单元测试包spring-test-4.0.0.RELEASE.jar
2、@ContextConfiguration(locations=” “)使用它来指定Spring配置文件的位置
@ContextConfiguration(locations="classpath:applicationContext.xml")
3、@RunWith指定用哪种驱动进行单元测试,默认就是junit
@RunWith(SpringJUnit4ClassRunner.class)
使用Spring的单元测试模块来执行标了@Test注解的测试方法
以前@Test注解只是由junit执行
好处:我们不用ioc.getBean()获取组件了;直接Autowired组件Spring为我们自动装配
@ContextConfiguration(locations="classpath:applicationContext.xml")
@RunWith(SpringJUnit4ClassRunner.class)
class IOCTest {
//ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml");
ApplicationContext ioc = null;
@Autowired
BookServlet bookServlet;
@Test
void test() {
Object bean2 = ioc.getBean("bookServlet");
}
@Test
void test2() {
BookServlet bookServlet = ioc.getBean(BookServlet.class);
bookServlet.doGet();
}
@Test
void test3() {
System.out.println(bookServlet);
}
}