如何在JUnit测试过程中,用Mock替换springContext中的Bean

如何在JUnit测试过程中,用Mock替换springContext中的Bean


      
        ServiceClientFacade mock 
=  createMock(ServiceClientImpl. class );
        
        ApplicationContext ac 
=   new  ClassPathXmlApplicationContext( " classpath:/applicationContext.xml " );
        AbstractRefreshableApplicationContext acc 
= (AbstractRefreshableApplicationContext)ac;
        DefaultListableBeanFactory bf 
=  (DefaultListableBeanFactory)acc.getBeanFactory();//get the beanFactory
        bf.destroySingletons();//清除已经实例了的singleton bean
        RootBeanDefinition rbd 
=   new  RootBeanDefinition(mock.getClass());
        bf.registerBeanDefinition(
" serviceClient " , rbd); //注册mock bean
        ServiceClientFacade m 
=  (ServiceClientFacade)ac.getBean( " serviceClient " );//get mock bean
        //下边是一些测试代码,供参考
        OpportunityFacade oppFacade 
=  (OpportunityFacade)ac.getBean( " oppFacade " );
        oppFacade.saveQuote(
null , null );
        System.out.println(m.closeNspProcess(
"" ));




你可能感兴趣的:(如何在JUnit测试过程中,用Mock替换springContext中的Bean)