Spring beans redefinition in unit test environment

前端 未结 13 1962
醉话见心
醉话见心 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:10

    You can also write your unit tests to not require any lookups at all:

    @ContextConfiguration(locations = { "classpath:/path/to/test-config.xml" })
    @RunWith(SpringJUnit4ClassRunner.class)
    public class MyBeanTest {
    
        @Autowired
        private MyBean myBean; // the component under test
    
        @Test
        public void testMyBean() {
            ...
        }
    }
    

    This gives an easy way to mix and match real config files with test config files.

    For example, when using hibernate, I might have my sessionFactory bean in one config file (to be used in both the tests and the main app), and have by dataSource bean in another config file (one might use a DriverManagerDataSource to an in-memory db, the other might use a JNDI-lookup).

    But, definitely take heed of @cletus's warning ;-)

提交回复
热议问题