Spring not autowiring in unit tests with JUnit

后端 未结 5 731
盖世英雄少女心
盖世英雄少女心 2020-12-03 02:33

I test the following DAO with JUnit:

@Repository
public class MyDao {

    @Autowired
    private SessionFactory sessionFactory;

    // Other stuff here

}
         


        
5条回答
  •  长情又很酷
    2020-12-03 03:01

    You need to use the Spring JUnit runner in order to wire in Spring beans from your context. The code below assumes that you have a application context called testContest.xml available on the test classpath.

    import org.hibernate.SessionFactory;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.test.context.ContextConfiguration;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    import org.springframework.transaction.annotation.Transactional;
    
    import java.sql.SQLException;
    
    import static org.hamcrest.MatcherAssert.assertThat;
    import static org.hamcrest.Matchers.startsWith;
    
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations = {"classpath*:**/testContext.xml"})
    @Transactional
    public class someDaoTest {
    
        @Autowired
        protected SessionFactory sessionFactory;
    
        @Test
        public void testDBSourceIsCorrect() throws SQLException {
            String databaseProductName = sessionFactory.getCurrentSession()
                    .connection()
                    .getMetaData()
                    .getDatabaseProductName();
            assertThat("Test container is pointing at the wrong DB.", databaseProductName, startsWith("HSQL"));
        }
    }
    

    Note: This works with Spring 2.5.2 and Hibernate 3.6.5

提交回复
热议问题