Spring beans redefinition in unit test environment

前端 未结 13 1783
醉话见心
醉话见心 2020-12-07 11:13

We are using Spring for my application purposes, and Spring Testing framework for unit tests. We have a small problem though: the application code loads a Spring application

13条回答
  •  有刺的猬
    2020-12-07 12:09

    I would propose a custom TestClass and some easy rules for the locations of the spring bean.xml:

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations = {
        "classpath*:spring/*.xml",
        "classpath*:spring/persistence/*.xml",
        "classpath*:spring/mock/*.xml"})
    @Transactional
    @TestExecutionListeners({
        DependencyInjectionTestExecutionListener.class,
        TransactionalTestExecutionListener.class,
        DirtiesContextTestExecutionListener.class})
    public abstract class AbstractHibernateTests implements ApplicationContextAware {
    
        /**
         * Logger for Subclasses.
         */
        protected final Logger log = LoggerFactory.getLogger(getClass());
    
        /**
         * The {@link ApplicationContext} that was injected into this test instance
         * via {@link #setApplicationContext(ApplicationContext)}.
         */
        protected ApplicationContext applicationContext;
    
        /**
         * Set the {@link ApplicationContext} to be used by this test instance,
         * provided via {@link ApplicationContextAware} semantics.
         */
        @Override
        public final void setApplicationContext(
                final ApplicationContext applicationContext) {
            this.applicationContext = applicationContext;
        }
    }
    

    If there are mock-bean.xml in the specified location, they will override all "real" bean.xml files in the "normal" locations - your normal locations might differ.

    But … I would never mix mock and non-mock beans, as it's hard to trace problems when the application grows older.

提交回复
热议问题