单元测试的错误示范:
    image.png
    当启动ioc容器时就会扫描所有组件,@Component就会被扫描到重复加载ioc容器无限套娃。

    1、导包
    Spring的单元测试包spring-test-4.0.0.RELEASE.jar
    image.png

    2、@ContextConfiguration(locations=” “)使用它来指定Spring配置文件的位置

    1. @ContextConfiguration(locations="classpath:applicationContext.xml")

    3、@RunWith指定用哪种驱动进行单元测试,默认就是junit
    @RunWith(SpringJUnit4ClassRunner.class)
    使用Spring的单元测试模块来执行标了@Test注解的测试方法
    以前@Test注解只是由junit执行
    好处:我们不用ioc.getBean()获取组件了;直接Autowired组件Spring为我们自动装配

    1. @ContextConfiguration(locations="classpath:applicationContext.xml")
    2. @RunWith(SpringJUnit4ClassRunner.class)
    3. class IOCTest {
    4. //ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml");
    5. ApplicationContext ioc = null;
    6. @Autowired
    7. BookServlet bookServlet;
    8. @Test
    9. void test() {
    10. Object bean2 = ioc.getBean("bookServlet");
    11. }
    12. @Test
    13. void test2() {
    14. BookServlet bookServlet = ioc.getBean(BookServlet.class);
    15. bookServlet.doGet();
    16. }
    17. @Test
    18. void test3() {
    19. System.out.println(bookServlet);
    20. }
    21. }